2016-05-31 62 views
3

社区!将intellij想法连接到sql server数据库

我目前正在使用真棒Intellij IDEA终极版学习Java。我试图连接到本地的SQL Server数据库,但我很难做到这一点。最初,我尝试使用内置的工具(我能够成功连接,但它看起来像是让我能够在它的Intellij控制台上运行SQL查询。更具体地说,我创建了一个基本的GUI客户可以在其中输入他们的个人信息,并且我希望将这些信息存储在Customers SQL表中。我也尝试使用JDBC,但出于某种原因,我得到错误“com.microsoft.sqlserver.jdbc.SQLServerDriver “我没有下载所需的驱动程序,并将它放在我的项目的lib文件夹中,但我不知道还有什么可以做的,我的猜测是我没有正确链接或将jar文件与驱动程序放在我的项目中。 Intellij文档对于SQL Tools来说是非常有限的,它只是基本的功能,如果有人能够在我的JDBC方法中指出我的错误,或者深入了解Intellij的SQL Tools,我会很感激。你先进的时间试图帮助这6个月老新手:) 这里是我的代码:

import java.sql.*; 
import javafx.application.Application; 
import javafx.geometry.Insets; 
import javafx.scene.*; 
import javafx.scene.control.Button; 
import javafx.scene.control.Label; 
import javafx.scene.control.TextField; 
import javafx.scene.layout.GridPane; 
import javafx.stage.Stage; 

public class Main extends Application { 

String name; 
Stage window; 
Scene scene; 
Button submitButton = new Button("Submit"); 
Label fNameLabel = new Label("First Name:"); 
Label lNameLabel = new Label("Last Name:"); 
Label birthDateLabel = new Label("DOB:"); 
Label addressLabel = new Label("Address:"); 
Label emailLabel = new Label("E-mail:"); 
Label phoneLabel = new Label("Phone:"); 
TextField fNameTextField = new TextField(); 
TextField lNameTextField = new TextField(); 
TextField birthDateTextField = new TextField(); 
TextField addressTextField = new TextField(); 
TextField emailTextField = new TextField(); 
TextField phoneTextField = new TextField(); 


public static void main(String args[]) { 

    launch(args); 

} 

@Override 
public void start(Stage primaryStage) throws Exception { 

    window = primaryStage; 
    window.setTitle("Customer Information"); 
    window.setOnCloseRequest(e -> { 
     e.consume(); 
     closeWindow(); 
    }); 

    //create GripPane scene 
    GridPane grid = new GridPane(); 
    grid.setPadding(new Insets(10,10,10,10)); 
    grid.setVgap(10); 
    grid.setHgap(10); 

    //set location of labels 
    GridPane.setConstraints(fNameLabel,3,0); 
    GridPane.setConstraints(lNameLabel,3,1); 
    GridPane.setConstraints(birthDateLabel,3,2); 
    GridPane.setConstraints(addressLabel,3,3); 
    GridPane.setConstraints(emailLabel,3,4); 
    GridPane.setConstraints(phoneLabel,3,5); 

    //set location of TextFields 
    GridPane.setConstraints(fNameTextField,4,0); 
    GridPane.setConstraints(lNameTextField,4,1); 
    GridPane.setConstraints(birthDateTextField,4,2); 
    GridPane.setConstraints(addressTextField,4,3); 
    GridPane.setConstraints(emailTextField,4,4); 
    GridPane.setConstraints(phoneTextField,4,5); 

    //set PromptText 
    birthDateTextField.setPromptText("mm/dd/yyyy"); 
    emailTextField.setPromptText("[email protected]"); 

    //set button location 
    GridPane.setConstraints(submitButton, 4, 6); 

    //add all elements to grid 
    grid.getChildren().addAll(fNameLabel,fNameTextField,lNameLabel,lNameTextField, 
           birthDateLabel,birthDateTextField,addressLabel,addressTextField, 
           emailLabel,emailTextField,phoneLabel,phoneTextField,submitButton); 

    scene = new Scene(grid, 400, 400); 

    window.setScene(scene); 
    window.show(); 

    } 

    //properly exit out of app 
    private void closeWindow() { 
    boolean answer = ConfirmationBox.display("title", "Are you sure you want to exit?"); 
     if (answer) { 
     window.close(); 
    } 
    } 
} 

SQL类试图连接:关于选择的IntelliJ

import java.sql.*; 
public class SQLMethods { 
    public static void main(String[] args) { 
    try { 
     Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 
     String url = "jdbc:sqlserver://localhost\\SQLEXPRESS:1433;databaseName=CaiMaster"; 

     Connection conn = DriverManager.getConnection(url); 
     Statement statement = conn.createStatement(); 
     ResultSet resultSet; 

     resultSet = statement.executeQuery("SELECT Fname, Address FROM Customers WHERE Fname = 'Cai'"); 
     String lastName = resultSet.getString("Fname"); 
     String address = resultSet.getString("Address"); 
     System.out.println(lastName); 
     System.out.println(address); 
     conn.close(); 
     } catch (Exception e) { 
     System.err.println("Got an exception! "); 
     System.err.println(e.getMessage()); 

    } 
    } 
    } 

回答

2

祝贺。 JetBrains毫无例外地成为市场上最好的IDE。

将依赖项下的/ lib目录添加到您的项目中,您将获得更多成功。

我不相信你的网址是正确的。尝试像这样,一旦你得到排序/ lib目录:

String url = "jdbc:sqlserver://localhost:1433;databaseName=CaiMaster"; 

试试这个,看看它是否效果更好:

/** 
* SQL utility methods 
* User: MDUFFY 
* Date: 5/31/2016 
* Time: 4:41 PM 
* @link http://stackoverflow.com/questions/37536372/connect-intellij-idea-to-sql-server-database/37536406?noredirect=1#comment62595302_37536406 
*/ 

import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.PreparedStatement; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.sql.Statement; 


public class SQLMethods { 

    public static final String DEFAULT_DRIVER_CLASS = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; 
    public static final String DEFAULT_URL = "jdbc:sqlserver://localhost:1433;databaseName=CaiMaster"; 
    private static final String DEFAULT_USERNAME = ""; 
    private static final String DEFAULT_PASSWORD = ""; 
    public static final String FIND_ALL_CUSTOMERS_QUERY = "SELECT Fname, Address FROM Customers "; 
    private static final String BY_FIRST_NAME = "WHERE FNAME = ? "; 


    public static void main(String[] args) { 
     Connection connection = null; 
     try { 
      connection = SQLMethods.getConnection(DEFAULT_DRIVER_CLASS, DEFAULT_URL, DEFAULT_USERNAME, DEFAULT_PASSWORD); 
      Customer customer = SQLMethods.findCustomer(connection, "Cai"); 
      System.out.println(customer); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } finally { 
      SQLMethods.close(connection); 
     } 
    } 

    public static Connection getConnection(String driverClass, String url, String username, String password) throws SQLException, ClassNotFoundException { 
     Class.forName(driverClass); 
     return DriverManager.getConnection(url, username, password); 
    } 

    public static void close(Connection connection) { 
     try { 
      if (connection != null) { 
       connection.close(); 
      } 
     } catch (SQLException e) { 
      e.printStackTrace(); 
     } 
    } 

    public static void close(Statement statement) { 
     try { 
      if (statement != null) { 
       statement.close(); 
      } 
     } catch (SQLException e) { 
      e.printStackTrace(); 
     } 
    } 

    public static void close(ResultSet resultSet) { 
     try { 
      if (resultSet != null) { 
       resultSet.close(); 
      } 
     } catch (SQLException e) { 
      e.printStackTrace(); 
     } 
    } 

    public static Customer findCustomer(Connection connection, String name) { 
     Customer customer = null; 
     PreparedStatement ps = null; 
     ResultSet rs = null; 
     try { 
      ps = connection.prepareStatement(FIND_ALL_CUSTOMERS_QUERY + BY_FIRST_NAME); 
      ps.setString(1, name); 
      rs = ps.executeQuery(); 
      while (rs.next()) { 
       String firstName = rs.getString("Fname"); 
       String address = rs.getString("Address"); 
       customer = new Customer(address, firstName); 
      } 
     } catch (SQLException e) { 
      e.printStackTrace(); 
     } finally { 
      SQLMethods.close(rs); 
      SQLMethods.close(ps); 
     } 
     return customer; 
    } 
} 

class Customer { 
    private final String firstName; 
    private final String address; 

    public Customer(String address, String firstName) { 
     this.address = address; 
     this.firstName = firstName; 
    } 

    public String getFirstName() { 
     return firstName; 
    } 

    public String getAddress() { 
     return address; 
    } 

    @Override 
    public String toString() { 
     final StringBuilder sb = new StringBuilder("Customer{"); 
     sb.append("firstName='").append(firstName).append('\''); 
     sb.append(", address='").append(address).append('\''); 
     sb.append('}'); 
     return sb.toString(); 
    } 
} 
+0

谢谢!这开始看起来更好。在项目依赖关系中添加jar文件有所帮助。在您的建议和其他人指出我缺少凭据后,它不会给我缺少的驱动程序错误,但是现在我收到错误“结果集没有当前行”。它的确如此。实际上它只有一行。有什么想法吗? –

+0

是的,你不使用典型的习惯用法来使用ResultSet。看一下JDBC教程。你需要调用next()来移动光标。 – duffymo

+0

先生你真棒,谢谢。出于某种原因,我虽然因为我只想要第一行,我不需要告诉光标移动。它现在像一种魅力。超级感谢! –

1

正如@duffymo说,我也是不知道的正确性你网址。另外,您在getConnection(url)方法中错过了您的用户名和密码。它应该是这样的:

String url = "jdbc:sqlserver://localhost\\SQLEXPRESS:1433;databaseName=CaiMaster"; 
    String username = "user"; 
    String password = "pass"; 
    Connection conn = DriverManager.getConnection(url,username,password); 

    Statement st = conn.createStatement(); 

希望这会有所帮助。让我知道。

+0

谢谢,是的,它帮助了一下。随着@duffymo建议加上你的我相信我连接,但是我仍然得到一个错误“结果集没有当前行”,当它正好有一行。我正在选择的那个。有任何想法吗? –