java对sql server的增删改查

时间:2023-03-10 03:41:46
java对sql server的增删改查
 package Database;
import java.sql.*;
public class DBUtil {
//这里可以设置数据库名称
private final static String URL = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=mythree";
private static final String USER="sa";
private static final String PASSWORD="123";
private static Connection conn=null;
//静态代码块(将加载驱动、连接数据库放入静态块中)
static{
try { //1.加载驱动程序
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//2.获得数据库的连接
conn=(Connection)DriverManager.getConnection(URL,USER,PASSWORD);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
//对外提供一个方法来获取数据库连接
public static Connection getConnection(){
return conn;
}
//查询
public void select(Statement stmt) throws SQLException {
ResultSet rs = stmt.executeQuery("select * from 李运辰.选课");
while(rs.next()){
//如果对象中有数据,就会循环打印出来
System.out.println("学号="+rs.getInt("学号")+"课程编号="+rs.getInt("课程编号")+"考试成绩="+rs.getInt("考试成绩")); //System.out.println(rs.getInt("教师编号")+","+rs.getString("姓名")+","+rs.getInt("专业"));
}
}
//插入
public void insert(Statement stmt) throws SQLException {
//成功-返回false
boolean execute = stmt.execute("insert into 李运辰.选课 values(1,2,100)");
System.out.println(execute);
}
//更新
public void update(Statement stmt) throws SQLException {
//返回序号
int executeUpdate = stmt.executeUpdate("update 李运辰.选课 set 考试成绩=90 where 学号=1 ");
System.out.println(executeUpdate);
}
//删除
public void delete(Statement stmt) throws SQLException {
//成功-返回false
boolean execute = stmt.execute("delete from 李运辰.选课 where 学号=11 and 课程编号=2");
System.out.println(execute);
}
//测试用例
public static void main(String[] args) throws Exception{
DBUtil d = new DBUtil();
//3.通过数据库的连接操作数据库,实现增删改查
Statement stmt = conn.createStatement();
//ResultSet executeQuery(String sqlString):执行查询数据库的SQL语句 ,返回一个结果集(ResultSet)对象。
//d.insert(stmt);
//d.update(stmt);
d.delete(stmt);
d.select(stmt); } }