Java DataBase Connectivity(Java语言连接数据库)
JDBC是SUN公司制定的一套接口(interface)
java.sql.*;
(这个软件包下有很多接口)
接口都有调用者和实现者。
面向接口调用、面向接口写实现类,这都属于面向接口编程。
解耦合:降低程序的耦合度,提高程序的扩展力。
多态机制就是非常典型的:面向抽象编程。(不要面向具体编程)
建议:
Animal a = new Cat();
Animal a = new Dog();
// 喂养的方法
public void feed(Animal a){ // 面向父类型编程。
}
不建议:
Dog d = new Dog();
Cat c = new Cat();
因为每一个数据库的底层实现原理都不一样。
Oracle数据库有自己的原理。
MySQL数据库也有自己的原理。
MS SqlServer数据库也有自己的原理。
…
每一个数据库产品都有自己独特的实现原理。
一套接口。
/*
SUN公司负责制定这套JDBC接口。
*/
public interface JDBC
{
/*
连接数据库的方法。
*/
void getConnection();
}
/*
MySQL的数据库厂家负责编写JDBC接口的实现类
*/
public class MySQL implements JDBC{
public void getConnection(){
//具体这里的代码怎么写,对于我们Java程序员来说没关系。
//这段代码涉及到MySQL底层数据库的实现原理。
System.out.println("连接MySQL数据库成功!");
}
}
//实现类被称为驱动。(MySQL驱动)
/*
Oracle的数据库厂家负责编写JDBC接口的实现类
*/
public class Oracle implements JDBC{
public void getConnection(){
//具体这里的代码怎么写,对于我们Java程序员来说没关系。
//这段代码涉及到Oracle底层数据库的实现原理。
System.out.println("连接Oracle数据库成功!");
}
}
//实现类被称为驱动。(Oracle驱动)
/*
SqlServer的数据库厂家负责编写JDBC接口的实现类
*/
public class SqlServer implements JDBC{
public void getConnection(){
//具体这里的代码怎么写,对于我们Java程序员来说没关系。
//这段代码涉及到SqlServer底层数据库的实现原理。
System.out.println("连接SqlServer数据库成功!");
}
}
//实现类被称为驱动。(SqlServer驱动)
//xxx.jar 当中有很多.class都是对JDBC接口进行的实现。
/*
Java程序员角色
不需要关心具体是哪个品牌的数据库,只需要面向JDBC 接口写代码。
面向接口编程、面向抽象编程,不要面向具体编程。
*/
public class JavaProgrammer
{
public static void main(String[] args) throws Exception{
//JDBC jdbc = new MySQL();
//JDBC jdbc = new Oracle();
//JDBC jdbc = new SqlServer();
//创建对象可以通过反射机制。
//Class c = Class.forName("MySQL");
//Class c = Class.forName("Oracle");
//Class c = Class.forName("SqlServer");
//通过配置文件获取
ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
String className = bundle.getString("className");
Class c = Class.forName(className);
JDBC jdbc = (JDBC)c.newInstance();
JDBC jdbc = (JDBC)c.newInstance();
//以下代码都是面向接口调用方法,不需要修改
jdbc.getConnection();
}
}
jdbc.properties
className=Oracle
直接在当前目录的地址栏下输入cmd,然后回车进入Dos窗口
javac *.java
编译
java Javaprogrammer
运行
查看环境变量中是否有classpath变量,如果上下都没有,新建如下:
输入变量名:classpath
变量值:.;D:\course\06-JDBC\resources\MySql Connector Java 5.1.23\mysql-connector-java-5.1.23-bin.jar
【注意】:.; 千万不可以省略。
. 代表当前路径,如果删掉这个点代表当前路径写死了,以后自己写的Java程序也没法运行了,因为会自动全到mysql-connector-java-5.1.23-bin.jar中找。
; 必须是英文的分号
以上的配置是针对于文本编辑器的方式开发,使用IDEA工具的时候,不需要配置以上的环境变量。
IDEA有自己的配置方式。
/*
JDBC 编程六步
*/
import java.sql.*;
public class JDBCTest01 {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
// 1、注册驱动
Driver driver = new com.mysql.jdbc.Driver();//多态,父类型引用指向子类型对象
//Driver driver = new com.oracle.jdbc.OracleDriver(); //Oracle的驱动
DriverManager.registerDriver(driver);
// 2、获取连接
/*
url:统一资源定位符(网络中某个资源的绝对路径)
https:www.baidu.com/ 这就是一个URL
url包括哪几部分:
协议
IP
Port
资源名
eg:baidu
http://182.61.200.7:80/index.html
http://通信协议
182.61.200.7 服务器IP地址
80 服务器上软件的端口
index.html 是服务器上某个资源名
jdbc:mysql://127.0.0.1:3306/bjpowernode
jdbc:mysql:// 协议
127.0.0.1 IP地址
3306 mysql数据库端口号
bjpowernode 具体的数据库实例名
说明:localhost和127.0.0.1都是本机IP地址。
什么是通信协议,有什么用?
通信协议是通信之前就提前定好的数据传送格式。
数据包具体怎么传数据,格式提前定好的。
*/
// static Connection getConnection(String url, String user, String password)
String url = "jdbc:mysql://127.0.0.1:3306/bjpowernode";
String user = "root";
String password = "333";
conn = DriverManager.getConnection(url,user,password);
System.out.println("数据库连接对象" + conn); //数据库连接对象com.mysql.jdbc.JDBC4Connection@1ae369b7
// 3、获取数据库操作对象(Statement专门执行sql语句的)
// Statement createStatement() 创建一个 Statement 对象来将 SQL 语句发送到数据库。
stmt = conn.createStatement();
// 4、执行sql语句
// int executeUpdate(String sql)
String sql = "insert into dept(deptno,dname,loc) values(50,'人事部','北京')";
//专门执行DML语句的(insert delete update)
// 返回值是“影响数据库中的记录条数”
int connt = stmt.executeUpdate(sql);
//合并语句
//int count = stmt.executeUpdate("update dept set dname = '销售部',loc = '合肥' where deptno = 20;");
System.out.println(count == 1 ? "保存成功":"保存失败");
// 5、处理查询结果集
} catch(SQLException e) {
e.printStackTrace();
} finally {
// 6、释放资源
//为了保障资源一定释放,在finally语句块中关闭资源
// 并且要遵循从小到大依次关闭
//分别对其try..catah
if(stmt != null) {
try {
stmt.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null) {
try {
conn.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
/*
JDBC完成Delete update
*/
import java.sql.*;
public class JDBCTest02 {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// 1、注册驱动
Driver driver = new com.mysql.jdbc.Driver();
DriverManager.registerDriver(driver);
// 2、获取连接
String url = "jdbc:mysql://127.0.0.1:3306/bjpowernode";
String user = "root";
String password = "333";
conn = DriverManager.getConnection(url,user,password);
// 3、获取数据库操作对象
stmt = conn.createStatement();
// 4、执行sql语句
//String sql = "delete from dept where deptno = 40";
//JDBC中的SQL语句不需要提供分号结尾。
String sql = "update dept set dname = '销售部',loc = '天津' where deptno = 20";
int connt = stmt.executeUpdate(sql);
//合并语句
//int count = stmt.executeUpdate("delete from dept where deptno = 50");
System.out.println(count == 1? "删除成功":"删除失败");
// 5、获取查询结果集
} catch(SQLException e){
e.printStackTrace();
} finally {
// 6、释放资源
if(conn != null) {
try {
conn.close();
} catch(SQLException e){
e.printStackTrace();
}
}
if(stmt != null) {
try {
stmt.close();
} catch(SQLException e){
e.printStackTrace();
}
}
}
}
}
/*
注册驱动的另一种方式(这种方式常用)
*/
import java.sql.*;
public class JDBCTest03 {
public static void main(String[] args) {
try{
// 注册驱动
//这是注册驱动的第一种写法
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//注册驱动的第二种方式;常用的。(反射机制)
//为什么这种方式常用?因为参数是一个字符串,字符串可以写到xxx.properties文件中。
//以下方法不需要接收返回值,因为我们只想用它的类加载动作。
Class.forName("com.mysql.jdbc.Driver");
// 获取连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","333");
System.out.println(conn);
} catch(SQLException e){
e.printStackTrace();
} catch(ClassNotFoundException e){
e.printStackTrace();
}
}
}
//将连接数据库的所有信息配置到配置文件中
/*
实际开放中不建议把连接数据库的信息写死到java程序中。
*/
import java.sql.*;
import java.util.*;
public class JDBCTest00 {
public static void main(String[] args) {
//使用资源绑定器绑定属性配置文件
ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
String driver = bundle.getString("driver");
String url = bundle.getString("url");
String user = bundle.getString("user");
String password = bundle.getString("password");
Connection conn = null;
Statement stmt = null;
try {
// 1、注册驱动
Class.forName(driver);
// 2、获取连接
conn = DriverManager.getConnection(url,user,password);
// 3、获取数据库操作对象
stmt = conn.createStatement();
// 4、执行sql语句
String sql = "update dept set dname = '销售部2',loc = '天津2' where deptno = 20";
int connt = stmt.executeUpdate(sql);
System.out.println(count == 1? "修改成功":"修改失败");
// 5、获取查询结果集
} catch(Exception e){
e.printStackTrace();
} finally {
// 6、释放资源
if(conn != null) {
try {
conn.close();
} catch(SQLException e){
e.printStackTrace();
}
}
if(stmt != null) {
try {
stmt.close();
} catch(SQLException e){
e.printStackTrace();
}
}
}
}
}
jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/bjpowernode
user=root
password=333
/*
处理查询结果集
*/
import java.sql.*;
import java.util.*;
public class JDBCTest005 {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
// 1、注册驱动
Class.forName("com.mysql.jdbc.Driver");
// 2、获取连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","333");
// 3、获取数据库操作对象
stmt = conn.createStatement();
// 4、执行sql语句
String sql = "select empno,ename,sal from emp";
// int executeUpdate(insert/delete/update)
// ResultSet executeQuery(select)
rs = stmt.executeQuery(sql);//专门执行DQL语句的方法。
// 5、获取查询结果集
while(rs.next()){
/*
//true
//光标指向的行有数据
//取数据
//getString()方法的特点是:不管数据库中的数据类型是什么,都以String的形式取出。
//以下程序的1,2,3说的是第几列
String empno = rs.getString(1);//JDBC中所有下标从1开始。不是从0开始。
String ename = rs.getString(2);
String sal = rs.getString(3);
System.out.println(empno + "," + ename + "," + sal);
*/
/*
// 按下标取出,程序不健壮,以下是以列的名字获取
String empno = rs.getString("empno");//重点注意:列名称不是表中的名称,是查询结果集的列名称
String ename = rs.getString("ename");
String sal = rs.getString("sal");
System.out.println(empno + "," + ename + "," + sal);
*/
/*
// 除了可以以String类型取出之外,还可以指定的类型取出
int empno = rs.getInt(1);
String ename = rs.getString(2);
double sal = rs.getDouble(3);
System.out.println(empno + "," + ename + "," + (sal + 100));
*/
int empno = rs.getInt("empno");
String ename = rs.getString("ename");
double sal = rs.getDouble("sal");
System.out.println(empno + "," + ename + "," + (sal + 200));
}
} catch(Exception e){
e.printStackTrace();
}finally{
// 6、释放资源
if(rs != null){
try{
rs.close();
} catch (Exception e){
e.printStackTrace();
}
}
if(stmt != null){
try{
stmt.close();
} catch (Exception e){
e.printStackTrace();
}
}
if(conn != null){
try{
conn.close();
} catch (Exception e){
e.printStackTrace();
}
}
}
}
}
遍历结果集
第一步:选中项目模块,单击右键选择如下菜单选项
第二步:选择库
第三步:选择java库
第四步:选择mysql驱动
第五步:选择导入到哪个模块
第六步:应用
引入成功
数据的准备
再次双击表格,进入设置,保存SQL脚本
数据没问题,使用工具可以正常显示
import java.sql.*;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Scanner;
/*
*
* 实现功能
* 1.需求:模拟实现用户登录功能
* 2.业务功能:
* 程序运行的时候,提供一个输入的入口,可以让用户输入用户名和密码
* 用户输入用户名和密码之后,提交信息,java程序收集到用户信息
* java程序连接数据库验证用户名和密码是否合法
* 合法:显示登录成功
* 不合法:显示登录失败
* 3.数据的准备
* 在实际开发中,表的设计会使用专业的建模工具,我们这里安装一个建模工具,powerDesigner
* 使用PD工具来进行数据表的设计
*
* 4.当前程序出现的问题
* 用户名:fdsa
* 密码:fdsa ' or '1'='1
* 登录成功
* 这种现象被称为SQL注入(安全隐患),(黑客经常使用)
* 5。导致SQL注入的最根本原因是什么?
*
* */
public class JDBCTest06 {
public static void main(String[] args) {
//初始化一个界面
Map<String,String> userLoginInfo = initUI();
//验证用户名和密码
boolean loginSuccess = login(userLoginInfo);
//最后输出结果
System.out.println(loginSuccess ? "登录成功" : "登录失败");
}
/**
* 用户登录
* @param userLoginInfo 用户登录信息
* @return false表示失败,true表示成功
*/
private static boolean login(Map<String, String> userLoginInfo) {
//打标记的意识
boolean loginSuccess = false;
//单独定义变量
String loginName = userLoginInfo.get("loginName");
String loginPwd = userLoginInfo.get("loginPwd");
//JDBC代码
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
//1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获取连接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=UTC","root","user");
//3.获取数据库操作对象
statement = connection.createStatement();
//4.执行SQL
String sql = "select * from t_user where loginName = '"+loginName+"' and loginPwd = '"+loginPwd+"'";
//String sql = "select * from t_user where loginName = '"+userLoginInfo.get("loginName")+"' and loginPwd = '"+userLoginInfo.get("loginPwd")+"'";
resultSet = statement.executeQuery(sql);
//5.处理结果集
if (resultSet.next()){
//登录成功
loginSuccess = true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//6.释放资源
if (resultSet != null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (statement != null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
return loginSuccess;
}
/**
* 初始化用户界面
* @return用户输入的用户名和密码等登录信息
*/
private static Map<String, String> initUI() {
Scanner s = new Scanner(System.in);
System.out.println("用户名:");
String loginName = s.nextLine();
System.out.println("密码:");
String loginPwd = s.nextLine();
Map<String,String> userLoginInfo = new HashMap<>();
userLoginInfo.put("loginName",loginName);
userLoginInfo.put("loginPwd",loginPwd);
return userLoginInfo;
}
}
【注意】:以下写法会报错。
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","user");
我用的是8.0.21,在新版的数据库使用的时区与本地时区有区别,标准时区使用的是Unix元年的时间为起始点到当前时间中间所做的动作。国际标准失去与本地相差 8 个小时。
解决方法:
在数据库名后面加 ?serverTimezone=UTC
UTC必须大写
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=UTC","root","user");
当前程序出现的问题
String sql = "select * from t_user where loginName = '"+loginName+"' and loginPwd = '"+loginPwd+"'";
//以上正好完成了SQL语句的拼接,以下代码的含义是,发送SQL语句给DBMS,DBMS进行SQL编译
//正好将用户提供的“非法信息”编译进去,导致原SQL语句的含义被扭曲了。
resultSet = statement.executeQuery(sql);
用户提供的信息中即使含有SQL语句的关键字,但是这些关键字并没有参与编译,不起作用。
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
/**
* 1.解决SQL注入问题?
* 只要用户提供的信息不参与SQL语句的编译过程,问题就解决了
* 即使用户提供的信息中含有SQL语句的关键字,但是没有参与编译,不起作用
* 要想用户信息不参与SQL语句的编译,那么必须使用java.sql.preparedStatement
* PreparedStatement接口继承了java.sql.Statement
* PreparedStatement是属于预编译的数据库操作对象。
* PreparedStatement的原理 是,预先对SQL语句的框架进行编译,然后再给SQL语句传“值”。
*2.测试结果
* 用户名:fdas
* 密码:fdas' or '1'='1
* 登录失败
*3.解决SQL注入的关键是什么?
* 用户提供的信息中即使含有SQL语句的关键字,但是这些关键字并没有参与编译,不起作用。
*/
public class JDBCTest07 {
public static void main(String[] args) {
//初始化一个界面
Map<String,String> userLoginInfo = initUI();
//验证用户名和密码
boolean loginSuccess = login(userLoginInfo);
//最后输出结果
System.out.println(loginSuccess ? "登录成功" : "登录失败");
}
/**
* 用户登录
* @param userLoginInfo 用户登录信息
* @return false表示失败,true表示成功
*/
private static boolean login(Map<String, String> userLoginInfo) {
//打标记的意识
boolean loginSuccess = false;
//单独定义变量
String loginName = userLoginInfo.get("loginName");
String loginPwd = userLoginInfo.get("loginPwd");
//JDBC代码
Connection connection = null;
PreparedStatement ps = null;//这里使用PreparedStatement(预编译的数据库操作对象)
ResultSet resultSet = null;
try {
//1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获取连接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=UTC","root","user");
//3.获取预编译的数据库操作对象
//SQL语句的框子。其中一个?,表示一个占位符,一个?将来接收一个“值”,【注意】,占位符不能使用单引号括起来。
String sql = "select * from t_user where loginName = ? and loginPwd = ?";
//程序执行到此处,会发送SQL语句的框子给DBMS,然后DBMS进行SQL语句的预先编译。
ps = connection.prepareStatement(sql);
//给占位符?传值(第1个问号下标是1,第2个问号下标是2,JDBC中所有下标从1开始)
ps.setString(1,loginName);
ps.setString(2,loginPwd);
//4.执行SQL
resultSet = ps.executeQuery();
//5.处理结果集
if (resultSet.next()){
//登录成功
loginSuccess = true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//6.释放资源
if (resultSet != null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (ps != null){
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
return loginSuccess;
}
/**
* 初始化用户界面
* @return用户输入的用户名和密码等登录信息
*/
private static Map<String, String> initUI() {
Scanner s = new Scanner(System.in);
System.out.println("用户名:");
String loginName = s.nextLine();
System.out.println("密码:");
String loginPwd = s.nextLine();
Map<String,String> userLoginInfo = new HashMap<>();
userLoginInfo.put("loginName",loginName);
userLoginInfo.put("loginPwd",loginPwd);
return userLoginInfo;
}
}
【综上所述】:PreparedStatement使用较多,只有较少数的情况下需要使用Statement。
使用PreparedStatement
import java.sql.*;
import java.util.Scanner;
public class JDBCTest08 {
public static void main(String[] args) {
//用户在控制台输入desc就是降序,输入asc就是升序
Scanner s = new Scanner(System.in);
System.out.println("请输入desc或asc,desc表示降序,asc表示升序");
System.out.println("请输入:");
String keyWords = s.nextLine();
//执行SQL
Connection connection = null;
PreparedStatement ps = null;
ResultSet resultSet = null;
try {
//注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//获取连接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=UTC","root","user");
//获取预编译的数据库操作对象
String sql = "select ename from emp order by ename ?";
ps = connection.prepareStatement(sql);
ps.setString(1,keyWords);
//执行SQL
resultSet = ps.executeQuery();
//遍历结果集
while (resultSet.next()){
System.out.println(resultSet.getString("ename"));
}
} catch (Exception e) {
e.printStackTrace();
}finally {
//释放资源
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
报错:
java.sql.SQLSyntaxErrorException:您的SQL语法有错误;检查与您的MySQL服务器版本相对应的手册,以在第1行的“ desc”附近使用正确的语法
请输入desc或asc,desc表示降序,asc表示升序
请输入:
desc
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''desc'' at line 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1003)
at JDBCTest08.main(JDBCTest08.java:27)
Process finished with exit code 0
使用 Statement
import java.sql.*;
import java.util.Scanner;
public class JDBCTest08 {
public static void main(String[] args) {
/*
//用户在控制台输入desc就是降序,输入asc就是升序
Scanner s = new Scanner(System.in);
System.out.println("请输入desc或asc,desc表示降序,asc表示升序");
System.out.println("请输入:");
String keyWords = s.nextLine();
//执行SQL
Connection connection = null;
PreparedStatement ps = null;
ResultSet resultSet = null;
try {
//注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//获取连接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=UTC","root","user");
//获取预编译的数据库操作对象
String sql = "select ename from emp order by ename ?";
ps = connection.prepareStatement(sql);
ps.setString(1,keyWords);
//执行SQL
resultSet = ps.executeQuery();
//遍历结果集
while (resultSet.next()){
System.out.println(resultSet.getString("ename"));
}
} catch (Exception e) {
e.printStackTrace();
}finally {
//释放资源
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}*/
//用户在控制台输入desc就是降序,输入asc就是升序
Scanner s = new Scanner(System.in);
System.out.println("请输入desc或asc,desc表示降序,asc表示升序");
System.out.println("请输入:");
String keyWords = s.nextLine();
//执行SQL
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
//注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//获取连接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=UTC","root","user");
//获取数据库操作对象
statement = connection.createStatement();
//执行SQL
String sql = "select ename from emp order by ename "+keyWords;
resultSet = statement.executeQuery(sql);
//遍历结果集
while (resultSet.next()){
System.out.println(resultSet.getString("ename"));
}
} catch (Exception e) {
e.printStackTrace();
}finally {
//释放资源
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
增加一条数据
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* PreparedStatement完成 INSERT DELETE UPDATE
*/
public class JDBCTest09 {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement ps = null;
try {
//注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//获取连接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=UTC","root","user");
//获取预编译的数据库操作对象
String sql = "insert into dept(deptno,dname,loc) values(?,?,?)";
ps = connection.prepareStatement(sql);
ps.setInt(1,60);
ps.setString(2,"销售部");
ps.setString(3,"上海");
//执行SQL
int count = ps.executeUpdate();
System.out.println(count);
} catch (Exception e) {
e.printStackTrace();
}finally {
//释放资源
if (ps == null) {
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection == null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
更改一条数据
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* PreparedStatement完成 INSERT DELETE UPDATE
*/
public class JDBCTest09 {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement ps = null;
try {
//注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//获取连接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=UTC","root","user");
//获取预编译的数据库操作对象
/*String sql = "insert into dept(deptno,dname,loc) values(?,?,?)";
ps = connection.prepareStatement(sql);
ps.setInt(1,60);
ps.setString(2,"销售部");
ps.setString(3,"上海");*/
String sql = "update dept set dname = ?,loc = ? where deptno = ?";
ps = connection.prepareStatement(sql);
ps.setString(1,"研发一部");
ps.setString(2,"北京");
ps.setInt(3,60);
//执行SQL
int count = ps.executeUpdate();
System.out.println(count);
} catch (Exception e) {
e.printStackTrace();
}finally {
//释放资源
if (ps == null) {
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection == null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
删除一条数据
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* PreparedStatement完成 INSERT DELETE UPDATE
*/
public class JDBCTest09 {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement ps = null;
try {
//注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//获取连接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=UTC","root","user");
//获取预编译的数据库操作对象
/*String sql = "insert into dept(deptno,dname,loc) values(?,?,?)";
ps = connection.prepareStatement(sql);
ps.setInt(1,60);
ps.setString(2,"销售部");
ps.setString(3,"上海");*/
/* String sql = "update dept set dname = ?,loc = ? where deptno = ?";
ps = connection.prepareStatement(sql);
ps.setString(1,"研发一部");
ps.setString(2,"北京");
ps.setInt(3,60);*/
String sql = "delete from dept where deptno = ?";
ps = connection.prepareStatement(sql);
ps.setInt(1,60);
//执行SQL
int count = ps.executeUpdate();
System.out.println(count);
} catch (Exception e) {
e.printStackTrace();
}finally {
//释放资源
if (ps == null) {
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection == null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* JDBC事务机制
* 1.JDBC中的事务是自动提交的,什么是自动提交?
* 只要执行任意一条DML语句,则自动提交一次,这是JDBC默认的事务行为。
* 但是在实际的业务当中,通常都是N条DML语句共同联合才能完成的,必须
* 保证他们这些DML语句在同一个事务中同时成功或者同时失败。
*
* 2.以下程序先来验证一下JDBC的事务是否是自动提交机制!
* 测试结果:JDBC中只要执行任意一条DML语句,就提交一次。
*
*/
public class JDBCTest10 {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement ps = null;
try {
//1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获取连接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=UTC","root","user");
//3.获取预编译的数据库操作对象
String sql = "update dept set dname = ? where deptno = ?";
ps = connection.prepareStatement(sql);
//第一次给占位符传值
ps.setString(1,"x部门");
ps.setInt(2,30);
int count = ps.executeUpdate();//执行第一条UPDATE语句
System.out.println(count);
//重新给占位符传值
ps.setString(1,"y部门");
ps.setInt(2,20);
count = ps.executeUpdate();//执行第二条UPDATE语句
System.out.println(count);
} catch (Exception e) {
e.printStackTrace();
}finally {
//6.释放资源
if (ps == null) {
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection == null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* sql脚本:
* drop table if exists t_act;
* create table t_act(
* actno int,
* balance double(7,2) //注意:7表示有效数据的个数,2表示小数位的个数。
* );
* insert into t_act(actno,balance) values(111,20000);
* insert into t_act(actno,balance) values(222,0);
* commit;
* select * from t_act;
*
* 批量编辑快捷键:Alt+shift+insert
*/
public class JDBCTest11 {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement ps = null;
try {
//1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获取连接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=UTC","root","user");
//3.获取预编译的数据库操作对象
String sql = "update t_act set balance = ? where actno = ?";
ps = connection.prepareStatement(sql);
//给?传值
ps.setDouble(1,10000);
ps.setInt(2,111);
int count = ps.executeUpdate();
//制造一个异常,这里坑定会出现空指针异常,
// 出现异常下边的代码将会不执行,直接进入catch语句块...
String s =null;
s.toString();
//给?传值
ps.setDouble(1,10000);
ps.setInt(2,222);
count += ps.executeUpdate();
System.out.println(count == 2 ? "转账成功" : "转账失败");
} catch (Exception e) {
e.printStackTrace();
}finally {
//6.释放资源
if (ps == null) {
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection == null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
刷新数据库
数据丢失了!!!!
不应该出现这种现象一半成功一半失败!关闭事务自动提交机制,必须同时成功或者同时失败!
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* sql脚本:
* drop table if exists t_act;
* create table t_act(
* actno int,
* balance double(7,2) //注意:7表示有效数据的个数,2表示小数位的个数。
* );
* insert into t_act(actno,balance) values(111,20000);
* insert into t_act(actno,balance) values(222,0);
* commit;
* select * from t_act;
*
* 批量编辑快捷键:Alt+shift+insert
*
* 重点三行代码:
* connection.setAutoCommit(false);//开启事务
* connection.commit();//提交事务
* connection.rollback();//回滚事务
*/
public class JDBCTest11 {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement ps = null;
try {
//1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获取连接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=UTC","root","user");
//将自动提交机制改为手动提交
connection.setAutoCommit(false);//开启事务
//3.获取预编译的数据库操作对象
String sql = "update t_act set balance = ? where actno = ?";
ps = connection.prepareStatement(sql);
//给?传值
ps.setDouble(1,10000);
ps.setInt(2,111);
int count = ps.executeUpdate();
//制造一个异常,这里坑定会出现空指针异常,
// 出现异常下边的代码将会不执行,直接进入catch语句块...
String s =null;
s.toString();
//给?传值
ps.setDouble(1,10000);
ps.setInt(2,222);
count += ps.executeUpdate();
System.out.println(count == 2 ? "转账成功" : "转账失败");
//程序能够走到这里说明以上程序没有异常,事务结束,手动提交数据
connection.commit();//提交事务
} catch (Exception e) {
//回滚事务
if (connection != null){
try {
connection.rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
e.printStackTrace();
}finally {
//6.释放资源
if (ps == null) {
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection == null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
数据是正常的!
注释掉异常之后,再刷新数据库!
import java.sql.*;
/**
* JDBC工具类,简化JDBC编程。
*
*/
public class DBUtil {
/**
* 工具类中的构造方法都是私有的
* 因为工具类当中的方法都是静态的,不需要new对象,直接采用类名调用。
*/
private DBUtil(){
}
//静态代码块在类加载时执行,并且只执行一次
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 获取数据库连接对象
* @return 连接对象
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=UTC","root","user");
}
/**
* 关闭资源
* @param connection 连接对象
* @param statement 数据库操作对象
* @param resultSet 结果集
*/
public static void close(Connection connection, Statement statement, ResultSet resultSet){
if (resultSet == null) {
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (statement == null) {
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection == null) {
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 这个程序两个任务
* 第一:测试DBUtil是否好用
* 第二:模糊查询怎么写?
*/
public class JDBCTest12 {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement ps = null;
ResultSet resultSet = null;
try {
//获取连接
connection = DBUtil.getConnection();
//获取预编译的数据库操作对象
//错误写法
/*String sql = "select ename from emp where ename like '_?%'";
ps = connection.prepareStatement(sql);
ps.setString(1,"A");*/
String sql = "select ename from emp where ename like ?";
ps = connection.prepareStatement(sql);
ps.setString(1,"_A%");
resultSet = ps.executeQuery();
while (resultSet.next()){
System.out.println(resultSet.getString("ename"));
}
} catch (Exception throwables) {
throwables.printStackTrace();
}finally {
//释放资源
DBUtil.close(connection,ps,resultSet);
}
}
}
悲观锁(行级锁 for update)和乐观锁机制
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 这个程序开启一个事务,这个事务进行查询,并且使用行级锁/悲观锁,锁住相关的记录
*/
public class JDBCTest13 {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement ps = null;
ResultSet resultSet = null;
try {
//获取连接
connection = DBUtil.getConnection();
//开启事务
connection.setAutoCommit(false);
String sql = "select ename,job,sal from emp where job = ? for update ";
ps = connection.prepareStatement(sql);
ps.setString(1,"MANAGER");
resultSet = ps.executeQuery();
while (resultSet.next()){
System.out.println(resultSet.getString("ename")+","+resultSet.getString("job")+","+resultSet.getgetDouble("sal"));
}
//提交事务(事务结束)
connection.commit();
} catch (Exception throwables) {
if (connection == null) {
try {
//回滚事务(事务结束)
connection.rollback();
} catch (SQLException throwables1) {
throwables1.printStackTrace();
}
}
throwables.printStackTrace();
}finally {
DBUtil.close(connection,ps,resultSet);
}
}
}
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* 这个程序负责修改你被锁定的记录
*/
public class JDBCTest14 {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement ps = null;
try {
connection = DBUtil.getConnection();
connection.setAutoCommit(false);
String sql = "update emp set sal = sal * 1.1 where job = ?";
ps = connection.prepareStatement(sql);
ps.setString(1,"MANAGER");
int count = ps.executeUpdate();
System.out.println(count);
connection.commit();
} catch (SQLException throwables) {
if (connection == null) {
try {
connection.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
throwables.printStackTrace();
}finally {
DBUtil.close(connection,ps,null);
}
}
}
下一篇:HTML基础语法
文章浏览阅读7.2k次。选择题题目:技术装备程度低、用人多、产品成本中活劳动消耗比重大的企业,属于() 企业。题目:市场渗透战略是由企业现有产品和( )结合而成的战略.题目:某牙膏厂原来只生产两面针药物牙膏,现在又增加牙刷生产,这属于( )。题目:在波士顿矩阵法中,( )类象限是指那些相对市场占有率较高和市场增长率较低的经营单位题目:以下哪种不是宏观环境分析考虑的因素( )题目:在《竞争战略》一书中提出了著名的五种竞争力量模型.题目:事业部制的缺点是与统一指挥原则相矛盾,容易产生职责不清的现象_下列说法错误的是 选择一项: a. 定量订货方式适合于品种数目少但占用资金大的b类
文章浏览阅读4.1k次,点赞5次,收藏15次。本文转载自http://blog.sina.com.cn/s/blog_149e9d2ec0102wyvq.htmlCRT原先是指Microsoft开发的C Runtime Library,用于操作系统的开发及运行。后来在此基础上开发了C++ Runtime Library,所以现在CRT是指Microsoft开发的C/C++ Runtime Library。在VC的CRT/SRC目录下,可以..._c++ crt
文章浏览阅读70次。【代码】C语言作业(四)
文章浏览阅读9.9k次。highlight.js是一款基于JavaScript的语法高亮库,目前支持125种编程语言,有63种可供选择的样式,而且能够做到语言自动识别,和目前主流的JS框架都能兼容,可以混合使用。这款高亮库可以用在博客系统中,其使用方法及其简单,几乎不需要任何学习成本,下面介绍highlight.js的使用。1.获取highlight.js库,用户可以从官网获取:地址:https://highlightjs_语法高亮js css文件
文章浏览阅读5.1k次。strftimestrftime是C语言标准库中用来格式化输出时间的的函数。下面是strftime的用法各参数意义代码使用示例#include<stdio.h>#include<time.h>#define print(s1, s2,s3) \ printf("%-20s%-30s%s\n",s1, s2,s3);int main(){ time_t rawtime; struct tm* timeinfo; char timE[80]; /
文章浏览阅读147次。传送门 01分数规划板题啊。 发现就是一个最优比率环。 这个直接二分+spfa判负环就行了。 代码:#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<cmath>#define N 1005#define...
文章浏览阅读9.3k次,点赞8次,收藏39次。知识点:第一个app,显示Helloworld一、创建一个空项目创建项目启动 Visual Studio。单击“文件”>“新建”>“项目”以创建新项目 。在“新建项目” 对话框中,单击“Android 应用” 模板。将新项目命名为Hello(Phoneword是微软示例,本人太懒,不改了),然后单击“确定” : 在“新 Android 应用” 对话框中,依次单击“BlankA..._c#开发app
文章浏览阅读267次,点赞5次,收藏9次。探索Camera2Demo:一款深入理解Android Camera2 API的开源示例项目项目地址:https://gitcode.com/wangshengyang1996/Camera2Demo项目简介Camera2Demo 是一个由wangshengyang1996开发并维护的Android应用示例,旨在帮助开发者更好地理解和使用Android的Camera2 API。该项目通过提供..._android camera2 demo
文章浏览阅读121次。2019独角兽企业重金招聘Python工程师标准>>> ...
文章浏览阅读10w+次。在做微信如:(退款、企业红包、企业付款)提现这些操作的时候,微信返回(具体哪个字段我忘记了)的信息是:证书过期,那么就需要重新获取证书,证书的获取前提条件:1:你需要有微信商户平台的商户号(类似电话号码的数字),和商户名称(比如公司名称)2:按照官方说明文档进行相应操作即可(按照这个做就行了)http://kf.qq.com/faq/161222NneAJf161222U7fARv.h..._微信 apiv3证书 过期
文章浏览阅读2.2k次。雷达探测是电磁威慑的重要组成。国外发达国家正从体系、平台、频段、架构、硬件、处理等方面开发新一代雷达技术。针对高超声速目标、弹道导弹、无人集群目标、隐身飞机等新型极高速、极隐身、极庞大目标,将以网络为基础,整合各类探测手段,实现对目标的全球预警、全程连续跟踪、全维协同精确打击,形成全域全时全维的体系化探测感知能力。对深空目标、临空目标、隐身目标、集群目标的探测研究新型威胁目标是驱动雷达探测技术前进的原动力之一,而新时期的新型威胁目标呈现“高、低、快、慢、小、隐、群”等特征。_探地雷达成像matlab
文章浏览阅读3.1k次,点赞2次,收藏12次。计算机取证 volatility_kali安装volatility