[关闭]
@PatrickCtyyx 2017-11-28T10:41:11.000000Z 字数 2270 阅读 1063

使用 Java 连接 SQL Server

作业


作者:程天阳

下载配置 JDBC 驱动

在 MS 官网下载 JDBC 驱动,链接点这里

Windows 版下载 exe 包,运行完成解压。然后把 Microsoft SQL Server JDBC Driver 3.0\sqljdbc_3.0\chs\auth\x64\sqljdbc_auth.dll文件 复制到C:\Windows\SysWOW64目录下。(64bit系统)

将 Microsoft SQL Server JDBC Driver 3.0\sqljdbc_3.0\chs\sqljdbc4.jar 包导入到项目中。我是使用 IntelliJ,参考这个教程

使用 Java 连接

  1. import java.sql.*;
  2. public class Main {
  3. public static void main(String[] args) {
  4. Connection conn = null; // 存储连接
  5. Statement stmt = null; // SQL 语句相关
  6. ResultSet rs = null; // 执行结果,只有查询语句才有结果
  7. // 数据库 url,用来连接 SQL Server
  8. // 注意这里不能使用 Windows 验证,因此要自己创建 login
  9. String url = "jdbc:sqlserver://localhost:1433;" +
  10. "databaseName=学生-课程;user=patrickcty;password=patrickcty";
  11. try {
  12. // 导入驱动
  13. Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
  14. conn = DriverManager.getConnection(url); // 建立连接
  15. // 连接检测
  16. if (conn != null) {
  17. System.out.println("Success connected!");
  18. }
  19. else {
  20. System.out.println("Not connected!");
  21. }
  22. // 创建语句对象
  23. stmt = conn.createStatement();
  24. String sql = "select * from student";
  25. // 查询语句用这个方法
  26. // 结果保存在 rs 中
  27. rs = stmt.executeQuery(sql);
  28. while (rs.next()) {
  29. System.out.println("学号:" + rs.getString(1) + "姓名:" + rs.getString(2));
  30. }
  31. // 插删改用这个方法
  32. sql = "insert into student values ('2015000021', '开普勒', '男', 25, '物理系')";
  33. stmt.executeUpdate(sql);
  34. sql = "update student set sdept = '文学系' where sname = '卡莲'";
  35. stmt.executeUpdate(sql);
  36. sql = "delete from student where sname = '开普勒'";
  37. stmt.executeUpdate(sql);
  38. sql = "select * from student";
  39. rs = stmt.executeQuery(sql);
  40. while (rs.next()) {
  41. System.out.println("学号:" + rs.getString(1) + "姓名:" + rs.getString(2));
  42. }
  43. sql = "create table test (id int)";
  44. stmt.executeUpdate(sql);
  45. sql = "select * from sysobjects where xtype='U'";
  46. rs = stmt.executeQuery(sql);
  47. while (rs.next()) {
  48. System.out.println("表名:" + rs.getString(1));
  49. }
  50. sql = "drop table test";
  51. stmt.executeUpdate(sql);
  52. }
  53. catch (Exception ex) {
  54. ex.printStackTrace();
  55. }
  56. // 关闭各种连接
  57. finally {
  58. try {
  59. if (rs != null) {
  60. rs.close();
  61. }
  62. if (stmt != null) {
  63. stmt.close();
  64. }
  65. if (conn != null) {
  66. conn.close();
  67. }
  68. }
  69. catch (Exception ex) {
  70. ex.printStackTrace();
  71. }
  72. }
  73. }
  74. }

遇到的问题

参考资料

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注