import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class test { public static void main(String[] args) { System.out.println("aaa"); try { String url = "jdbc:mysql://localhost:3306/demo1?" + "user=root&password=root&useUnicode=true&characterEncoding=UTF8"; Class.forName("com.mysql.jdbc.Driver"); Connection con= DriverManager.getConnection(url); // 创建查询 Statement st=con.createStatement(); // 添加数据 String sqlAdd="insert into student(sname,spass) values(‘掌柜的‘,‘1236547‘)"; int add=st.executeUpdate(sqlAdd); if(add!=0) { System.out.println("添加数据成功!"); } // 删除数据 String sqlDel="delete from student where sid=2"; int del=st.executeUpdate(sqlDel); if(del!=0) { System.out.println("删除成功!"); } // 更新数据 String sqlUpdate="update student set sname=‘战鹰‘ where sname=‘wanghu‘"; int a= st.executeUpdate(sqlUpdate); // 判断是否更新成功 if(a!=0) { System.out.println("修改成功"); } // 查询结果 String sqlSelect="select * from student"; ResultSet rs= st.executeQuery(sqlSelect); while(rs.next()) { int id=rs.getInt("sid"); String name=rs.getString("sname"); String pass=rs.getString("spass"); System.out.println("id="+id+", name="+name+", pass="+pass); } } catch (Exception e) { e.printStackTrace(); System.out.println(e.getMessage()); } } }
连接mysql数据库需要导入对应的驱动jar
mysql-connector-java-5.0.8-bin.jar
时间: 2024-11-04 15:36:44