public static void main(String[] args) {
// JDBC
Connection conn=null;
Statement sta=null;
try {
// 1.加载驱动
// jdbc5 com.mysql.jdbc.Driver
// jdbc8 com.mysql.cj.jdbc.Driver
String driver_m="com.mysql.cj.jdbc.Driver";
Class.forName(driver_m);
// 2.获取数据库连接
// "jdbc:mysql://localhost/test01?" localhost:本地连接 test01:数据名
String url_mysql = "jdbc:mysql://localhost/hzh0904?" + "useUnicode=ture&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8";
// 用户名
String user_name="root";
// 密码
String user_pass="root";
// 获取连接
conn = DriverManager.getConnection(url_mysql,user_name,user_pass);
// 3.设置事务(非必要)
conn.setAutoCommit(false);//手动提交
// 4.创建语句对象
sta=conn.createStatement();
// 5.执行sql语句
// 增删改 用executeUpdate 接收用 int(影响了几条数据)
String sql ="insert into student values (21,'一一',12,'女',90,2)";
String sql3 ="delete from student where id='21'";
int count = sta.executeUpdate(sql3);
System.out.println("插入了"+count+"条数据");
// 查询用 executeQuery 接收用 ResultSet String sql="select * from student"; ResultSet re= sta.executeQuery(sql);
// 第二种
// 4.创建预编译语句对象
String sql= "insert into student values(?,?,?,?,?,?)";
pre=conn.prepareStatement(sql);
// 5.执行sql
// pre.setString(字段的位置(非下标),字段内容);
pre.setString(1,"23");
ResultSet re= pre.executeQuery();
//1. Statement 先创建对象在写sql 在 execute中存储sql,并运行
// 2. PreparedStatement 先写sql 在创建对象里运行sql,用execute运行
// 6.提交事务
conn.commit();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}finally {
// 7.关闭连接
try {
sta.close();
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
// 判断表是否存在
DatabaseMetaData meta = m_sqlCon.getMetaData();
ResultSet rsTables = meta.getTables(null , null, “YourTableName”, null);
if(rsTables.next()){ System.out.println("The Table exsits."); }
else{ System.out.println("The Table not exsits."); }