@[小小库](java连接数据库)
package sql_one;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class main {
public static void main(String[] args) {
Connection con;
String str="com.microsoft.sqlserver.jdbc.SQLServerDriver";
String url="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=MBOOK";
String user="sa";
String password="123";
try {
Class.forName(str);//加载jdbc驱动程序
System.out.println("数据库驱动加载成功");
con=DriverManager.getConnection(url, user, password);
if(!con.isClosed())
System.out.println("Succeeded connecting to the Database");
Statement statement=con.createStatement();
//创建statement类对象,用来执行生气了SQL语句
String sql="select *from TABLE1";
//ResultSet类,用来存放获取的结果集
ResultSet rs=statement.executeQuery(sql);
String a[]=new String[100];
String b[]=new String[100];
System.out.println("执行结果如下所示:");
int i;
/*for( i=0;i<100;i++) {
a[i]=rs.getString("ID");
b[i]=rs.getString("NAME");
rs.next();
System.out.println("姓名:"+b[i]+"\t"+"书本ID:"+a[i]);
}*/
while(rs.next())
{
System.out.println(rs.getString("NAME"));
}//输出结果集的内容
rs.close();
/*String bookname=null;
String publiser=null;
while(rs.next()) {
bookname=rs.getString("BookName");
publiser=rs.getString("Pnubliser");
System.out.println(bookname+"\t"+publiser);
}
rs.close();
con.close();*/
}catch(ClassNotFoundException e) {
//数据库连接失败异常处理
System.out.println("sorry,can not find the Driver!");
e.printStackTrace();
}catch(SQLException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}finally {
System.out.println("数据库操作完成");
}
}
}