JDBC 数据删除,增加,及数据库信息查询
package com.dgd.test;
import java.sql.*;
public class DBTest {
//mysql驱动包名
private static final String DRIVER_NAME = "com.mysql.jdbc.Driver";
//数据库连接地址
// ?useSSL=false不校验ssl证书
// jdbc:mysql://这是协议,localhost:3306这是地址和端口,test这是数据库
private static final String URL = "jdbc:mysql://localhost:3306/test?useSSL=false";
//用户名,更换成你自己的用户名,此处为root用户
private static final String USER_NAME = "root";
//密码,更换成你自己设定的密码,此处为:123456
private static final String PASSWORD = "123456";
public static void main(String[] args) {
Connection connection = null;
try {
//加载mysql的驱动类
Class.forName(DRIVER_NAME);
//获取数据库连接
connection = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
DatabaseMetaData dbmd = connection.getMetaData();
System.out.println("数据库名:/t"+dbmd.getDatabaseProductName());
System.out.println("数据库产品版本:/t"+dbmd.getDatabaseProductVersion());
System.out.println("驱动版本:/t"+dbmd.getDriverVersion());
// 获取数据库服务器用作类别和表名之间的分隔符 如test.user
System.out.println("数据库和表分隔符:\t"+dbmd.getCatalogSeparator());
// 获取数据库名称
ResultSet rs = dbmd.getCatalogs();
while (rs.next()) {
System.out.println("数据库名称:\t"+rs.getString(1));
}
Boolean isDel = true;
if(true){
//打断后面执行语句
}else if(isDel){
String sql = "delete from user where id = ?;";
PreparedStatement prst = connection.prepareStatement(sql);
for (int i = 0; i < 5; i++) {
prst.setInt(1,i);
prst.execute();
}
prst.setInt(1,20);
prst.execute();
prst.close();
}else {
String sql = "insert into user values(null,?,?,?,?)";
PreparedStatement prst = connection.prepareStatement(sql);
for (int i = 0; i < 5; i++) {
prst.setString(1, "提莫lam"+i);
prst.setFloat(2, i+10);
prst.setInt(3, i);
prst.setInt(4, i+100);
prst.execute();
}
prst.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}