连接Sql Server 2008数据库的Java代码

package JDBC_Test;

3 import java.sql.SQLException;
4 import java.sql.Statement;
5 import java.sql.Connection;
6 import java.sql.DriverManager;
7 import java.sql.ResultSet;
8
9 public class Test {
10 public static void main(String[] args) {
11 Connection conn;
12 Statement stmt;
13 ResultSet rs;
14 String url = “jdbc:sqlserver://localhost:1433;DatabaseName=student_course;”;
15 String sql = “select * from student”;
16 try {
17 // 连接数据库
18 conn = DriverManager.getConnection(url, “sa”, “12345”);
19 // 建立Statement对象
20 stmt = conn.createStatement();
21 /**
22 * Statement createStatement() 创建一个 Statement 对象来将 SQL 语句发送到数据库。
23 /
24 // 执行数据库查询语句
25 rs = stmt.executeQuery(sql);
26 /
*
27 * ResultSet executeQuery(String sql) throws SQLException 执行给定的 SQL
28 * 语句,该语句返回单个 ResultSet 对象
29 */
30 while (rs.next()) {
31 int id = rs.getInt(“Sno”);
32 String name = rs.getString(“Sname”);
33 int age = rs.getInt(“Sage”);
34 System.out.println(“Sno:” + id + “\tSame:” + name + “\tSage:” + age);
35 }
36 if (rs != null) {
37 rs.close();
38 rs = null;
39 }
40 if (stmt != null) {
41 stmt.close();
42 stmt = null;
43 }
44 if (conn != null) {
45 conn.close();
46 conn = null;
47 }
48 } catch (SQLException e) {
49 e.printStackTrace();
50 System.out.println(“数据库连接失败”);
51 }
52 }
53 }

2.spring.xml写法:
1
2
3
4
5
6
7

打开编辑可看





3.jdbc.properties写法:
1
2
3
4
5
6
7
8
9

jdbc.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc.url=jdbc:sqlserver://localhost:1433;DatabaseName=数据库名称
jdbc.username=账号
jdbc.password=密码
jdbc.initialSize=0
jdbc.maxActive=20
jdbc.maxIdle=20
jdbc.minIdle=1
jdbc.maxWait=60000

猜你喜欢

转载自blog.csdn.net/qq_30347133/article/details/86466594