DBHelper.java
package school; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class DBHelper { public static final String url="jdbc:mysql://127.0.0.1/school?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false"; public static final String name="com.mysql.cj.jdbc.Driver"; public static final String user="root"; public static final String password="root"; public Connection conn=null; public PreparedStatement pst=null; public DBHelper(String sql) throws Exception{ Class.forName(name); //指定连接类型 conn=DriverManager.getConnection(url,user,password);//获取连接 pst=conn.prepareStatement(sql);//准备执行语句 } public void close() throws SQLException{ this.conn.close(); this.pst.close(); } }
Insert.java
package school; public class Insert { static String sql=null; static DBHelper db=null; static int ret=0; public static void main(String[]args) throws Exception{ sql="insert into t_student values('11','prince','m')";//sql语句 db=new DBHelper(sql); ret=db.pst.executeUpdate(sql); System.out.println("成功加入"+ret+"行"); } }
Update.java
package school; import java.sql.ResultSet; public class Update { static String sql=null; static DBHelper db=null; static int ret=0; public static void main(String[] args) throws Exception { // TODO Auto-generated method stub sql="update t_student set stuname='prince2021' where stuno='1'" ; db=new DBHelper(sql); ret=db.pst.executeUpdate(sql); System.out.println("成功更新"+ret+"行"); } }
Select.java
package school; import java.sql.ResultSet; public class Select { static String sql=null; static DBHelper db=null; static ResultSet ret=null; public static void main(String[]args) throws Exception{ sql="select * from t_student";//SQL语句 db=new DBHelper(sql); ret=db.pst.executeQuery();//执行语句,得到结果集 while(ret.next()){ String id=ret.getString(1); String name=ret.getString(2); String sex=ret.getString(3); System.out.println(id+"\t"+name+"\t"+sex); } ret.close(); db.close(); } }
Delete.java
package school; public class Delete { static String sql=null; static DBHelper db=null; static int ret=0; public static void main(String[]args) throws Exception{ sql="delete from t_student where stusex='m'";//sql语句 db=new DBHelper(sql); ret=db.pst.executeUpdate(sql); System.out.println("成功shan删除"+ret+"行"); } }