增删改查
增(插入):
public static void insertStudent ( String sno, String sex) throws ClassNotFoundException , SQLException {
String url= "jdbc:mysql://localhost:3406/testdb?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC" ;
String dbUser = "root" ;
String dbPassword = "123456789" ;
String driverName= "com.mysql.cj.jdbc.Driver" ;
Class . forName ( driverName) ;
Connection conn= DriverManager . getConnection ( url, dbUser, dbPassword) ;
String sql= "insert into student(sno,sex) values('" + sno+ "','" + sex+ "')" ;
Statement statement= conn. createStatement ( ) ;
int lines= statement. executeUpdate ( sql) ;
System . out. println ( "lines=" + lines) ;
statement. close ( ) ;
conn. close ( ) ;
}
String sql="insert into student(sno,sex) values('"+sno+"','"+sex+"') "; //增删改查的区别行
String sql="update student set sex='"+sex+"' where sno='"+sno+" '";
String sql="delete from student where sno='"+sno+" ' ";
String sql = "Select * from student where sno='"+sno+" ' ";
查:
public static void selectStudentBySno ( String sno) throws ClassNotFoundException , SQLException {
String url= "jdbc:mysql://localhost:3406/testdb?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC" ;
String dbUser = "root" ;
String dbPassword = "123456789" ;
String driverName= "com.mysql.cj.jdbc.Driver" ;
Class . forName ( driverName) ;
Connection conn= DriverManager . getConnection ( url, dbUser, dbPassword) ;
String sql = "Select * from student where sno='" + sno+ "'" ;
Statement statement = conn. createStatement ( ) ;
ResultSet rs = statement. executeQuery ( sql) ;
while ( rs. next ( ) ) {
String sno2 = rs. getString ( "sno" ) ;
String sex = rs. getString ( "sex" ) ;
System . out. println ( "sno=" + sno2+ ",sex=" + sex) ;
}
rs. close ( ) ;
statement. close ( ) ;
conn. close ( ) ;
}