使用Java语言编程实现对学生-课程数据库的访问,使用者可以进行创建、插入、查询、删除和更新等操作。
import java.sql.*;
public class jdbc {
public static void main(String[] args) throws SQLException {[添加链接描述](https://blog.csdn.net/chen_xu_yuan/article/details/76164923)
// TODO 自动生成的方法存根
Connection con = null;
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); //加载驱动程序
}catch(ClassNotFoundException e){
System.out.println("找不到驱动程序类 ,加载驱动失败!");
e.printStackTrace() ;
}
String url=("jdbc:sqlserver://localhost:1433;DatabaseName=Test");//预先定义好连接所需参数
String user="sa";
String password="Gjk140319";
try{
con=DriverManager.getConnection(url, user, password); //连接数据库
}catch(SQLException e){
System.out.println("数据库连接失败!");
e.printStackTrace() ;
}
Statement statement1 = con.createStatement();
ResultSet result= statement1.executeQuery("select Cno,grade from SC where Sno='201215123'");
System.out.println("学号为201215123地同学的成绩为:");
while(result.next())
{
//得到记录值,输出
String Cno = result.getString("Cno");
String grade= result.getString("grade");
System.out.println("课程号: "+ Cno+" 成绩: "+grade );
}
/*创建新表*/
Statement statement2 = con.createStatement();
statement2.executeUpdate("create table JDBC(name nvarchar(5),age smallint)");
/*插入操作*/
Statement statement3 = con.createStatement();
statement3.executeUpdate("insert into Students values('201215129',N'二货',N'男',19,'IS')");
/*删除操作*/
Statement statement4 = con.createStatement();
statement4.executeUpdate("delete from SC where Sno='201215125' and Cno='8'");
/*更新操作*/
Statement statement5 = con.createStatement();
statement5.executeUpdate("update SC set grade='89' where Sno='201215121' and Cno='1'");
}
}