2016-05-31 12 views
3

コミュニティに接続してください!intellijアイデアをSQLサーバーデータベース

私は現在、素晴らしいIntellij IDEA Ultimateエディションを使用してJavaを学習しています。私はローカルのSQL Serverデータベースに接続しようとしていますが、そうするのは苦労しています。当初は、組み込みのツールを使用してみましたが(これは正常に接続できましたが、Intellijコンソール上でSQLクエリを実行できるようになっているようですが、より具体的には基本的なGUIを作成しました顧客が自分の個人情報を入力することができ、その情報をCustomers SQLテーブルに保存したいのですが、私もJDBCを使用しようとしましたが、何らかの理由で "com.microsoft.sqlserver.jdbc.SQLServerDriver "私は、必要なドライバをダウンロードしてプロジェクトのlibフォルダに配置しましたが、それ以外のことはわかりません。私の推測では、私のプロジェクトのjarファイルをドライバーに正しくリンクしていません。 Intellijのドキュメントは、SQLツールに関しては非常に限定されていますが、基本的な機能にのみ移動します。この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ディレクトリを追加すると、より多くの成功を収めます。

あなたのURLが正しいとは思わないです。

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ファイルをプロジェクトの依存関係に追加することは助けになりました。あなたの提案と他の誰かが私が信任状を紛失していることを指摘した後、それは私に不足しているドライバのエラーを与えませんでしたが、今は "結果セットに現在の行がありません"というエラーが出ます。それは確かにします。実際には1行しかありません。何かご意見は? –

+0

はい、通常のイディオムを使用してResultSetを使用していません。 JDBCチュートリアルを見てください。カーソルを進めるにはnext()を呼び出す必要があります。 – duffymo

+0

あなたは素晴らしいです、ありがとうございます。私はちょうど最初の行が欲しかったので何らかの理由でカーソルを移動する必要はありませんでした。それは今の魅力のように機能します。スーパー感謝!! –

1

@duffymoは、私もあなたの正確性について確認していない、言ったようにあなたはソート/ libディレクトリを得れば、このようにそれを試してみてくださいurl。また、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の提案とあなたの意見では、私は接続されていると信じていますが、「結果セットには現在行がありません」というエラーが表示されます。私は選択しています。何か案は? –

関連する問題