22,301
社区成员




package pkg;
import java.sql.*;
//import java.sql.DriverManager;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
String driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver";
String dbURL="jdbc:sqlserver://localhost:49420;DatabaseName=Test";
String userName="zwq";
String userPwd="qwe123456";
try
{
Class.forName(driverName);
Connection dbConn=DriverManager.getConnection(dbURL,userName,userPwd);
System.out.println("连接数据库成功");
try{
dbConn.close();
System.out.println("断开数据库成功");
}catch(Exception e){
System.out.println("断开数据库失败");
}
}
catch(Exception e)
{
e.printStackTrace();
System.out.print("连接失败");
}
//rs.close();
//stmt.close();
}
}
package edition1;
import java.sql.*;
import java.math.*;
import java.lang.*;
public class Main {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
static final String DB_URL = "jdbc:sqlserver://localhost:49420;DatabaseName=Test";
// Database credentials
static final String USER = "zwq";
static final String PASS = "qwe123456";
public static void main(String[] args) {
/*String PASS = "qwe123456";
String USER = "zwq";
String JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String DB_URL = "jdbc:sqlserver://localhost:49420;DatabaseName=TestJdbc";*/
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
}catch(Exception e){
e.printStackTrace();
System.out.println("Class.forName错误");
}
//STEP 3: Open a connection
System.out.println("Connecting to database...");
try{
conn = DriverManager.getConnection(DB_URL,USER,PASS);
}catch(Exception e){
e.printStackTrace();
System.out.println("conn错误");
}
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT bookId FROM DHB";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
//int age = rs.getInt("age");
//String first = rs.getString("first");
//String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
/*System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);*/
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
System.out.println("JDBC捕捉");
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
System.out.println("class.forname捕捉");
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample