java - 将intellij idea连接到sql server数据库

标签 java sql-server jdbc intellij-idea

社区!

我目前正在使用出色的 Intellij IDEA 终极版学习 Java。我正在尝试连接到本地 SQL Server 数据库,但我很难这样做。最初,我尝试使用内置工具(我能够成功连接,但似乎所做的只是让我能够在 Intellij 控制台上运行 SQL 查询。更具体地说,我创建了一个基本的 GUI客户可以在其中输入他们的个人信息,我希望将该信息存储在 Customers SQL 表中。我也尝试使用 JDBC,但由于某种原因我收到错误“com.microsoft.sqlserver.jdbc.SQLServerDriver “。我确实下载了所需的驱动程序,并将其放在我项目的 lib 文件夹中,但我不知道还能做什么。我的猜测是我没有正确链接或将 jar 文件与我的项目中的驱动程序一起放置。JetBrain 的Intellij 文档在 SQL 工具方面非常有限。它只涉及基本功能。如果有人可以查明我在 JDBC 方法上的错误,或者可能更深入地了解 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("example@example.com");

    //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 类:

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());

    }
   }
  }

最佳答案

在 dependencies 下将/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();
    }
}

关于java - 将intellij idea连接到sql server数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37536372/

相关文章:

java - Redisson客户端setnx

sql-server - SSIS 包应该在数据库 SQL Server 还是单独的应用服务器上运行?

sql-server - 扩展第三方数据库的最佳实践?

Java ResultSet 为空但实际上不应该为空

java - java中的MySQL数据库,连接太多

java - 逐行读取CSV文件并解析它

java - java中哪个更快

java - 如果我在命令行中输入 Ctrl-C,Java 中的 finally block 还会执行吗?

sql-server - 实时系统数据库使用

java - 如何使用 Vert.x 从 JDBC + Java 获取数据到 Javascript?