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基础语法
文章浏览阅读90次。IPFire 2.21核心更新130发布了,提供x86_64、i586、arm版本下载,这是一个紧急更新,包含各种错误修复和大量安全修复程序的版本,搭载Linux 4.14.103、gcc 7.3.0、samba 3.6.25组件,以下是更新的详细内容。IPFire 2.21 Core Update 130主要更新注:IPFire 2.21 Core Update 130包含以下软件包的安全更新,..._ipfire arm
文章浏览阅读1k次。个人观点:当处理海量小文件时,先将小文件进行sequenceFile操作或者类似操作处理,然后再上传到HDFS系统进行下一步的处理。(如有其它建议,欢迎留言)一、直接上传本地栅格数据将导致的问题根据栅格数据的特点,每层的图片个数都为上层数量的四倍。在第20层时,仅仅第20层的图片的数量达到了“2199023255552”张(世界地图在第一层被切成了两张图片,第二十层的数量为:4**7*2),且..._local.liststatus(new path)
文章浏览阅读1.7k次。寒小阳目录视图摘要视图订阅 找工作知识储备(3)---从头说12种排序算法:原理、图解、动画视频演示、代码以及笔试面试题目中的应用分类: 笔试面试基础知识 算法那些事儿2013-09-29 16:54 9366人阅读 评论(10) 收藏 举报12种排序算法原理代码图解flash视频对应笔试面_排序算法考察
文章浏览阅读1.4k次,点赞28次,收藏22次。树是n (n≥0)个结点的有限集合,n=0时,称为空树,这是一种特殊情况。在二叉树中,如果是兄弟关系就在右边,如果是孩子就在左边 ,本质上,用二叉链表存储森林。上图这样一棵树的先根遍历顺序和二叉树的很像,按照二叉树的方法。上图这样一棵树的后根遍历顺序和二叉树的很像,按照二叉树的方法。中序遍历森林中第一棵树的根结点的子树森林。1)有且仅有一个特定的称为根的结点。_森林中的兄弟关系
文章浏览阅读152次。文件夹1Bayesian model selection贝叶斯模型选择1奥卡姆剃刀Occams razor原理2Computing the marginal likelihood evidence2-1 BIC approximation to log marginal ..._a.students.guide.to.bayesian.statistics
文章浏览阅读1.6w次,点赞7次,收藏58次。RDP是Windows的远程桌面协议。我们要暴力破解3389号端口的前提是对方的3389号端口是开放的,不过大多数情况下电脑是默认关闭的,即使有远程协助的需要也不一定非得要用到3389号端口,开启不仅容易被对方破解,还容易成为肉鸡如果你发现你的端口是开放的,那么我建议你还是关上吧。用nmap查看目标端口是否开放。..._kali 3389
文章浏览阅读868次,点赞2次,收藏5次。DIV半通明完成,运用CSS完成DIV成半透明效果,CSS实现层与后台半通明成果。一、DIV CSS半通明底子介绍设置装备摆设DIV半通明CSS代码:div{filter:alpha(Opacity=80);-moz-opacity:0.5;opacity:0.5;}阐明: 1、filter:对win IE设置半通明滤镜成就,filter:alpha(Opacity=80)代表该对象80%半透明..._html 背景div层
当system函数的参数是"shutdown"时,它将会执行系统的关机命令。具体来说,的功能是向操作系统发送一个关机信号,请求关闭计算机。这将触发操作系统执行一系列的关机操作,包括关闭所有正在运行的程序、保存必要的系统信息、并最终关闭计算机的电源。需要注意的是,执行通常需要管理员权限,因为关机操作涉及到系统级别的资源管理。在不同的操作系统上,关机命令可能会有所不同,因此具体的实现细节可能会有所差异。总结来说,是一个用于触发计算机关机操作的命令,通过调用外部的关机命令来实现这一功能。通过改变。
文章浏览阅读348次。本章节的阅读对象是对机器学习和 TensorFlow 都不太了解的新手.就像我们学习编程的第一步往往是学习敲出 "Hello World" 一样,机器学习的入门就要知道 MNIST.MNIST 是一个入门级的计算机视觉数据集,它包含各种手写数字图片:它也包含每一张图片对应的标签,告诉我们这个是数字几;比如,上面这四张图片的标签分别是 5, 0, 4, 1。在此教程中,我们将训练一个机器学习模型用于..._python 自己拍摄手写数字的图片。根据前面训练得到的分类器,自行设计数据预处理流
文章浏览阅读2k次。我正在创建一个界面,我需要打开一个新的窗口,点击一个按钮。所以我创建了主窗口,创建了所有按钮,并在一个类下创建了新窗口。我不完全确定是否需要,但我也会包括这一部分信息。对python来说是新的,如果它充满了错误,那么很抱歉。如果有人也能回答在打开另一个窗口时如何隐藏主菜单,那就太好了。干杯。import wxversionwxversion.select("2.8")import wxclass ..._wxpython点击按钮出现新窗口
文章浏览阅读3.4k次,点赞3次,收藏29次。一.单选题二.填空题三.判断题一.单选题静态链接是在( )进行的。A、编译某段程序时B、装入某段程序时C、紧凑时D、装入程序之前Pentium处理器(32位)最大可寻址的虚拟存储器地址空间为( )。A、由内存的容量而定B、4GC、2GD、1G分页系统中,主存分配的单位是( )。A、字节B、物理块C、作业D、段在段页式存储管理中,当执行一段程序时,至少访问()次内存。A、1B、2C、3D、4在分段管理中,( )。A、以段为单位分配,每._系统抖动现象的发生由什么引起的
文章浏览阅读2.4k次。在实际的工作生产中,零件的加工制造一般都需要二维工程图来辅助设计。UG NX 的工程图主要是为了满足二维出图需要。在绘制工程图时,需要先确定所绘制图形要表达的内容,然后根据需要并按照视图的选择原则,绘制工程图的主视图、其他视图以及某些特殊视图,最后标注图形的尺寸、技术说明等信息,即可完成工程图的绘制。1.视图选择原则工程图合理的表达方案要综合运用各种表达方法,清晰完整地表达出零件的结构形状,并便于看图。确定工程图表达方案的一般步骤如下:口分析零件结构形状由于零件的结构形状以及加工位置或工作位置的不._ug-nx工程图