package cn.kgc;
import java.sql.*;
/**
* Hello world!
*
*/
public class App
{
/**
* select host,user,authentication_string from user;
* grant all on *.* to root@'%' identified by 'kb12'; //所有的库 里面的 所有的表的所有权限授权给root@%用户 并设置密码kb12;
* @param args
* @throws ClassNotFoundException
* @throws SQLException
*/
public static void main( String[] args ) throws ClassNotFoundException, SQLException {
//1.装载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.1 3个常量字符串
final String URL = "jdbc:mysql://localhost:3306/schooldb?useSSL=true&useUnicode=true&characterEncoding=utf8";
final String USER = "root";
final String PASS = "abc123";
//开启远程连接的权限 ----------------------mysql 5.7
//2.2 创建连接对象 navicat也需要连接数据库
Connection con = DriverManager.getConnection(URL,USER,PASS);
//3 与mysql服务器交流
//增删改
/*final String SQL = "insert into employee(empName,empPos) values(?,?),(?,?)"; //管子
PreparedStatement pst = con.prepareStatement(SQL); //泵
pst.setObject(1,"郝丽娟"); //?
pst.setObject(2,"就业专员"); //第
pst.setObject(3,"陈海勇"); //?
pst.setObject(4,"教员"); //第*/
//删除
/*final String SQL = "delete from employee where empId in(?,?)";
PreparedStatement pst = con.prepareStatement(SQL); //泵
pst.setObject(1,2); //?
pst.setObject(2,3);*/
/*//修改
final String SQL = "update employee set empPos=? where empId = ?";
PreparedStatement pst = con.prepareStatement(SQL); //泵
pst.setObject(1,"就业专员"); //?
pst.setObject(2,4);
//4 向mysql服务执行SQL命令
int rowsAffected = pst.executeUpdate();
//5 根据rowsAffected输出执行结果
System.out.println(rowsAffected); //看看 是成功还是失败了*/
//查询
final String SQL = "select empId id,empName name,empPos pos from employee";
//⭐⭐⭐⭐⭐预编译sql执行器
//有3中statement prepared防止sql注入 ? 不能传一个 sql语句 ?只能是值
//?如果能传 在?中传sql命令 可以操作我们的数据库 这很危险
PreparedStatement pst = con.prepareStatement(SQL); //泵
//⭐普通执行器 这种不能防止sql注入
Statement statement = con.createStatement();
//⭐⭐⭐函数或存储过程执行器 自定义函数的执行器
CallableStatement callableStatement = con.prepareCall(SQL);
/*
* ResultSet
* MetaData 元数据(实体映射所依:反射)
* Data 结果数据
* */
ResultSet set = pst.executeQuery();
//结构
ResultSetMetaData md = set.getMetaData();
final int CC = md.getColumnCount();
for (int i = 1; i <= CC; i++) {
System.out.print(md.getColumnName(i)+"\t");
System.out.print(md.getColumnLabel(i)+"\t");
System.out.print(md.getColumnType(i)+"\t");
System.out.println(md.getColumnTypeName(i));
}
//结果集中的数据信息
while (set.next()) {
System.out.print(set.getObject(1).toString()+"\t");
System.out.print(set.getObject(2).toString()+"\t");
System.out.println(set.getObject(3).toString());
System.out.println(set.getObject(1).getClass().getName() + "\t");
System.out.println(set.getObject(2).getClass().getName() + "\t");
System.out.println(set.getObject(3).getClass().getName() + "\t");
}
//6 释放资源
set.close();
pst.close();
con.close();
}
}
jdbc 连接mqsql数据库 并实现 增删改查 的命令行实现
最新推荐文章于 2023-05-02 16:37:33 发布