JAVA连接数据库最后的执行语句怎么写?

2025-03-18 23:22:14
推荐回答(1个)
回答(1):

package com.jdbc;
import java.sql.*;public class SQLServerTest { public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String url="jdbc:microsoft:sqlserver://localhost:1433;DataBaseName=pubs";
String sql = "select * from jobs";

try{
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
conn = DriverManager.getConnection(url ,"sa","sa");
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()){
String res = rs.getString(1);
System.out.println(res);
}
} catch(ClassNotFoundException e) {
e.printStackTrace();
} catch(SQLException e) {
e.printStackTrace();
} finally {
try{
if(conn != null){
conn.close();
conn = null;
}
if(stmt != null){
stmt.close();
stmt = null;
}
if(rs != null){
rs.close();
rs = null;
}
} catch(SQLException e) {
e.printStackTrace();
}
}
}}