我用的mysql8.0版本数据库,驱动也是8.0版本,这个新版本不需要加载驱动
代码如下:
import java.sql.*;
import java.util.Scanner;
public class MySql {
private static final String url="jdbc:mysql://localhost:3306/fjs?serverTimezone=GMT%2B8&&useSSL=false";
private static final String username="root";
private static final String password="123456";
Scanner scanner=new Scanner(System.in);
public Connection getconn()//获取数据库连接
{
Connection conn=null;
try {
conn=DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
System.out.println("数据库连接失败");
e.printStackTrace();
}
return conn;
}
public ResultSet select() throws SQLException //查询
{
System.out.println("请输入要查询的表名");
String tabel=scanner.next();
System.out.println("请输入要查询的字段");
String field=scanner.next();
ResultSet rs = null;
try {
Connection conn=getconn();
String sql="select "+field+" from "+tabel+";";
PreparedStatement prs=conn.prepareStatement(sql);
rs=prs.executeQuery();
String [] str=array(field);
while (rs.next()) {
for(int i=0;i<str.length;i++)
{
System.out.print(rs.getString(str[i])+"---");
}
System.out.println();
}
close(conn, prs);
rs.close();
} catch (Exception e) {
System.out.println("查询失败");
e.printStackTrace();
}
return rs;
}
public void update() //修改
{
try {
Connection conn=getconn();
System.out.println("请输入要修改的表名");
String table=scanner.next();
System.out.println("要修改的字段+值");
String str=scanner.next();
System.out.println("判断条件");
String strbool=scanner.next();
String sql="update "+table+" set "+str+" where "+strbool+";";
PreparedStatement prs=conn.prepareStatement(sql);
prs.executeUpdate();
System.out.println("修改成功");
close(conn, prs);
} catch (SQLException e) {
System.out.println("修改失败");
e.printStackTrace();
}
}
public void insert()//插入
{
try {
Connection conn=getconn();
System.out.println("请输入要插入的Table");
String table=scanner.next();
System.out.println("插入表的字段");
String field=scanner.next();
System.out.println("需要插入的值");
String str=scanner.next();
String sql="insert into "+table+" ("+field+") "+"values("+str+");";
PreparedStatement pre=conn.prepareStatement(sql);
pre.executeUpdate();
System.out.println("插入成功");
close(conn, pre);
} catch (Exception e) {
// TODO: handle exception
}
}
public void delete()//删除
{
try {
Connection conn=getconn();
System.out.println("请输入要删除的表名");
String table=scanner.next();
System.out.println("判断条件");
String strbool=scanner.next();
String sql="delete from "+table+" where "+strbool+";";
PreparedStatement pre=conn.prepareStatement(sql);
pre.executeUpdate();
System.out.println("删除成功");
close(conn, pre);
} catch (Exception e) {
System.out.println("删除失败");
e.printStackTrace();
}
}
public void close(Connection conn,PreparedStatement pre) throws SQLException //关闭jdbc对象
{
conn.close();
pre.close();
System.out.println("连接关闭");
}
public String[] array(String str) //对用户输入进行字符串分割
{
String [] array=str.split(",");
return array;
}
public static void main(String[] args) {
try {
MySql aMySql=new MySql();
aMySql.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
}