packagecom.mysqltest;importjava.sql.Connection;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.SQLException;/** mysql增删改查*/
public classWork {/** insert 增加*/
public static intinsert() {
MySQLConnection connection= newMySQLConnection();
Connection conns;//获取连接
PreparedStatement pst; //执行Sql语句
int i = 0;
String sql= "insert into user (username,password) values(?,?)";try{
conns=connection.conn();
pst=conns.prepareStatement(sql);
pst.setString(1, "lizi");
pst.setString(2, "123");
i=pst.executeUpdate();
pst.close();
conns.close();
}catch(SQLException e) {
System.out.println("数据写入失败");
e.printStackTrace();
}returni;
}/** select 写入*/
public static voidselect() {
MySQLConnection connection= newMySQLConnection();
Connection conns;//获取连接
PreparedStatement pst; //执行Sql语句(Statement)
ResultSet rs; //获取返回结果
String sql = "select * from user";try{
conns=connection.conn();
pst=conns.prepareStatement(sql);
rs= pst.executeQuery(sql);//执行sql语句
System.out.println("---------------------------------------");
System.out.println("名字 | 密码");while(rs.next()) {
System.out.println(rs.getString("username") + " | " + rs.getString("password"));
}
System.out.println("---------------------------------------");
conns.close();
pst.close();
rs.close();
}catch(SQLException e) {
System.out.println("数据查询失败");
e.printStackTrace();
}
}/** update 修改*/
public static intupdate() {
MySQLConnection connection= newMySQLConnection();
Connection conns;//获取连接
PreparedStatement pst; //执行Sql语句(Statement)
int i = 0;
String sql= "update user set password = ? where username = ?";try{
conns=connection.conn();
pst=conns.prepareStatement(sql);
pst.setString(1, "123");
pst.setString(2, "lizi");
i=pst.executeUpdate();
pst.close();
conns.close();
}catch(SQLException e) {
System.out.println("数据修改失败");
e.printStackTrace();
}returni;
}/** delete 删除*/
public static intdelete() {
MySQLConnection connection= newMySQLConnection();
Connection conns;//获取连接
PreparedStatement pst; //执行Sql语句(Statement)
int i = 0;
String sql= "delete from user where username = ?";try{
conns=connection.conn();
pst=conns.prepareStatement(sql);
pst.setString(1, "lizi");
i=pst.executeUpdate();
pst.close();
conns.close();
}catch(SQLException e) {
System.out.println("数据删除失败");
e.printStackTrace();
}returni;
}/** test*/
public static voidmain(String[] args) {//System.out.println(insert());
select();//System.out.println(update());//System.out.println(delete());
}
}