|
public class UseExecuteQuery{
/**
* @param args
*/
public static void main(String[] args) {
String url=”jdbc:microsoft:sqlserver://localhost:1433;DataBaseName=jsp_test”;
String userName=”sa”;
String password=”";
String sql=null;
Connection conn=null;
Statement stmt=null;
try{
//第一步:加载驱动器
Class.forName(”com.microsoft.jdbc.sqlserver.SQLServerDriver”);
System.out.println(”加载成功”);
}
catch(ClassNotFoundException e){
System.out.print(”ClassNotFoundException”);
System.out.print(”加载驱动器类时出现异常”);
}
try{
//第二步:调用DriverManager.getConnection 静态方法得到数据库连接
conn=DriverManager.getConnection(url,userName,password);
System.out.println(”连接成功”);
//创建statement
stmt=conn.createStatement();
sql=”select * from student where stu_id='12′”;
//sql=”INSERT INTO student(stu_id,name,address,birthdate,age)”+”VALUES('12′,'zhangjun','shanghai','1984/07/01′,'23′)”;
//stmt.executeUpdate(”delete from student where stu_id='12′”);
ResultSet rs=stmt.executeQuery(sql);
//System.out.println(”Insert a row successful”);
while(rs.next()){
String id=rs.getString(1);
String name=rs.getString(2);
String address=rs.getString(3);
System.out.println(id+” “+name+” “+address);
}
rs.close();
stmt.close();
}
catch(SQLException e){
System.out.println(e.getMessage());
System.out.println(”出现sqlException 异常”);
}
finally{
try{
System.out.println(”关闭数据库的连接”);
//关闭语句和数据库连接
//stmt.close();
if(conn!=null)
conn.close();
}
catch(SQLException e){
System.out.println(”Close SQLException”);
System.out.println(”关闭数据库连接时出现异常”);
}
}
}
}
数据库连接也可通过连接池。 |
|
|