实验要求:
编写一个应用程序,连接SQL Server数据库Stu,并访问表中的内容输出
如下图所示:
数据库内容
java界面显示内容:
代码:
import java.sql.*;
public class test {
public static void main(String args[]){
String url="jdbc:sqlserver://localhost:1433;DatabaseName=Stu";
String driver="com.microsoft.sqlserver.jdbc.SQLServerDriver";
Statement sql;
ResultSet rs;
Connection con=null;
try{
Class.forName(driver);
}
catch(ClassNotFoundException event)
{System.out.print("无法创建驱动程式实体!");
}
try{
con=DriverManager.getConnection(url,"sa","123456");//连接代码
con.setAutoCommit(true);
System.out.println("已经连接到数据库....");
}
catch(SQLException e){
System.out.println(e);
}
try{
sql=con.createStatement();
rs=sql.executeQuery("SELECT * FROM students");
System.out.println("数据库的内容是:");
while(rs.next()){
String sno=rs.getString(1);
String sname=rs.getString(2);
String sex=rs.getString(3);
System.out.printf("%s\t",sno);
System.out.printf("%s\t",sname);
System.out.printf( "%s\n",sex);
}
con.close();
}
catch(SQLException e){
System.out.println(e);
}
}
}