java对sql server的增删改查
1 package Database; 2 import java.sql.*; 3 public class DBUtil { 4 //这里可以设置数据库名称 5 private final static String URL = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=mythree"; 6 private static final String USER="sa"; 7 private static final String PASSWORD="123"; 8 private static Connection conn=null; 9 //静态代码块(将加载驱动、连接数据库放入静态块中) 10 static{ 11 try { 12 13 //1.加载驱动程序 14 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 15 //2.获得数据库的连接 16 conn=(Connection)DriverManager.getConnection(URL,USER,PASSWORD); 17 } 18 catch (ClassNotFoundException e) { 19 e.printStackTrace(); 20 } catch (SQLException e) { 21 e.printStackTrace(); 22 } 23 } 24 //对外提供一个方法来获取数据库连接 25 public static Connection getConnection(){ 26 return conn; 27 } 28 //查询 29 public void select(Statement stmt) throws SQLException { 30 ResultSet rs = stmt.executeQuery("select * from 李运辰.选课"); 31 while(rs.next()){ 32 //如果对象中有数据,就会循环打印出来 33 System.out.println("学号="+rs.getInt("学号")+"课程编号="+rs.getInt("课程编号")+"考试成绩="+rs.getInt("考试成绩")); 34 35 //System.out.println(rs.getInt("教师编号")+","+rs.getString("姓名")+","+rs.getInt("专业")); 36 } 37 } 38 //插入 39 public void insert(Statement stmt) throws SQLException { 40 //成功-返回false 41 boolean execute = stmt.execute("insert into 李运辰.选课 values(1,2,100)"); 42 System.out.println(execute); 43 } 44 //更新 45 public void update(Statement stmt) throws SQLException { 46 //返回序号 47 int executeUpdate = stmt.executeUpdate("update 李运辰.选课 set 考试成绩=90 where 学号=1 "); 48 System.out.println(executeUpdate); 49 } 50 //删除 51 public void delete(Statement stmt) throws SQLException { 52 //成功-返回false 53 boolean execute = stmt.execute("delete from 李运辰.选课 where 学号=11 and 课程编号=2"); 54 System.out.println(execute); 55 } 56 //测试用例 57 public static void main(String[] args) throws Exception{ 58 DBUtil d = new DBUtil(); 59 //3.通过数据库的连接操作数据库,实现增删改查 60 Statement stmt = conn.createStatement(); 61 //ResultSet executeQuery(String sqlString):执行查询数据库的SQL语句 ,返回一个结果集(ResultSet)对象。 62 //d.insert(stmt); 63 //d.update(stmt); 64 d.delete(stmt); 65 d.select(stmt); 66 67 } 68 69 70 }
耐得住寂寞,才能登得顶
Gitee码云:https://gitee.com/lyc96/projects