三.本期教程的最后一项:删除数据
如果你看了上面的教程,这一步几乎都不用怎么看了,所以直接放代码
public void setdelect(String delect)//接收删除指令
{
try {
mysql mysql=new mysql();
mysql.url_mysql();
Statement stmt = mysql.conn.createStatement();
stmt.execute(delect);
System.out.println("数据删除成功");
}
catch (SQLException e)
{
e.printStackTrace();
}
}
package java_mysql;
public class main {
public static void main(String[] args)
{
update_mysql date=new update_mysql();
date.setdelect("delete from xxxx where 编号 in(15)");
}
}
这里顺便提一下删除方式,删除单删与多删:
"delete from xxxx where 编号=15"//单删
"delete from xxxx where 编号 in(15,1,3,4,6)"//多删
本期教程到此结束,java_mysql的对接交互教程暂时到此为止
释放本期代码:
package java_mysql;
import java.sql.*;
public class update_mysql {
public void setupdate(String date)
{
try { mysql mysql=new mysql();
mysql.url_mysql();
Statement stmt = mysql.conn.createStatement();
stmt.execute(date);
System.out.println("修改成功");
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public void setinput(String input)//添加方法
{
try { mysql mysql=new mysql();
mysql.url_mysql();
Statement stmt = mysql.conn.createStatement();
stmt.execute(input);
System.out.println("数据添加成功");
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public void setdelect(String delect)
{
try {
mysql mysql=new mysql();
mysql.url_mysql();
Statement stmt = mysql.conn.createStatement();
stmt.execute(delect);
System.out.println("数据删除成功");
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
package java_mysql;
public class main {
public static void main(String[] args)
{
//更新数据
update_mysql date=new update_mysql();
date.setupdate("UPDATE xxxx SET 编号='3',姓名='Tom',年龄=66,性别=1,生日='2020-06-26',邮箱='Tom@gmail.com',手机号='1357984541' where 编号=1");
//添加数据
update_mysql date=new update_mysql();
date.setinput("insert into xxxx values(null,'linda',56,'0','2000-11-15','Linda123@qq.com',1855676415)");
//删除数据
update_mysql date=new update_mysql();
date.setdelect("delete from xxxx where 编号 in(15)");
}
}
连接数据库代码:
package java_mysql;
import java.sql.*;
public class mysql {
private String userName = "root";
private String password = "123456";
private String url = "jdbc:mysql://localhost:3306/nvshen";
Connection conn = null;
public String url()
{
return url;
}
public String name()
{
return userName;
}
public String mima()
{
return password;
}
public void url_mysql() {
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("驱动加载成功!");
}
catch (ClassNotFoundException e)
{
System.out.println("加载失败!");
e.printStackTrace();
}
try
{
mysql aa=new mysql();
conn= DriverManager.getConnection(aa.url(),aa.name(), aa.mima());
System.out.println("数据库连接成功!");
}
catch (SQLException e)
{
e.printStackTrace();
System.out.println("连接失败!");
}
}
}