发布网友 发布时间:2022-04-27 05:13
共4个回答
懂视网 时间:2022-05-03 07:00
而Class.forName("com.mysql.jdbc.Driver");
通过查看源码,在com.mysql.jdbc.Driver类中存在静态代码块
public class Driver extends NonRegisteringDriver implements java.sql.Driver {
//
// Register ourselves with the DriverManager
//
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
静态方法:
static Connection getConnection(String url,String user,String password) 试图建立到给定数据库 URL 的连接。
用于执行静态 SQL 语句并返回它所生成结果的对象。
package cn.learn.jdbc;
import java.sql.*;
public class JdbcDemo01 {
public static void main(String[] args) {
//1.导入厂商jar包,复制包到新建文件夹lib,再add as Library
/*
mysql厂商的jar包在5版本后里的META-INF中已经注册驱动,可 以不写
Class.forName("com.mysql.jdbc.Driver");
*/
Statement statement = null;
Connection conn = null;
ResultSet count = null;
try {
//2.注册驱动,加载进内存
Class.forName("com.mysql.jdbc.Driver");
//3.获取数据库连接对象
conn = DriverManager.getConnection("jdbc:mysql:/// db1","root","123");
//4.定义SQL语句,语句不加分号
String sql = " select * from student ";
//5.获取执行sql的对象,Statement
statement = conn.createStatement();
//6.执行SQL
count = statement.executeQuery(sql);
//7.处理结果,打印在控制台
//7.1 先让光标移动一行,进入数据区域
while(count.next()){
System.out.print(count.getInt(1)+"-----");
System.out.print(count.getString(2)+"-----");
System.out.print(count.getInt(3)+"-----");
System.out.print(count.getDouble(4)+"-----");
System.out.println(count.getDate(5));
}
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}finally {
//8.释放资源,如果在第5步之前出现异常,执行进来statement 为空,则会出现空指针异常
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(count != null){
try {
count.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
/*
1-----小白-----15-----85.6-----1996-02-03
2-----小王-----13-----88.2-----null
3-----as-----88-----89.2-----null
8-----小白白-----0-----0.0-----null
9-----小白-----15-----75.6-----1996-02-03
*/
public class JDBCUtils {
private static String url;
private static String user;
private static String password;
private static String driver;
/**
* 文件的读取,只需要读取一次即可拿到这些值。使用静态代码块
*/
static{
//读取资源文件,获取值。
try {
//1. 创建Properties集合类。
Properties pro = new Properties();
//获取src路径下的文件的方式--->ClassLoader 类加载器
ClassLoader classLoader = JDBCUtils.class.getClassLoader();
URL res = classLoader.getResource("jdbc.properties");
String path = res.getPath();
System.out.println(path);
pro.load(new FileReader(path));
//3. 获取数据,赋值
url = pro.getProperty("url");
user = pro.getProperty("user");
password = pro.getProperty("password");
driver = pro.getProperty("driver");
//4. 注册驱动
Class.forName(driver);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 获取连接
* @return 连接对象
*/
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
/**
* 释放资源
* @param stmt
* @param conn
*/
public static void close(Statement stmt,Connection conn){
if( stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if( conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 释放资源
* @param stmt
* @param conn
*/
public static void close(ResultSet rs,Statement stmt, Connection conn){
if( rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if( stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if( conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
CREATE TABLE USER(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32),
PASSWORD VARCHAR(32)
);
INSERT INTO USER VALUES(NULL,'zhangsan','123');
INSERT INTO USER VALUES(NULL,'lisi','234');
public class JDBCDemo9 {
public static void main(String[] args) {
//1.键盘录入,接受用户名和密码
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名:");
String username = sc.nextLine();
System.out.println("请输入密码:");
String password = sc.nextLine();
//2.调用方法
boolean flag = new JDBCDemo9().login(username, password);
//3.判断结果,输出不同语句
if(flag){
//登录成功
System.out.println("登录成功!");
}else{
System.out.println("用户名或密码错误!");
}
}
/**
* 登录方法
*/
public boolean login(String username ,String password){
if(username == null || password == null){
return false;
}
//连接数据库判断是否登录成功
Connection conn = null;
prepareStatement pstmt = null;
ResultSet rs = null;
//1.获取连接
try {
conn = JDBCUtils.getConnection();
//2.定义sql
String sql = "select * from user where username = ? and password = ?";
//3.获取执行sql的对象
pstmt = conn.prepareStatement(sql);
//设置通配符传给需要的对象
pstmt.setString(1,username);
pstmt.setString(2,password);
//4.执行查询,不需要传参
rs = pstmt.executeQuery();
//5.判断
/* if(rs.next()){//如果有下一行,则返回true
return true;
}else{
return false;
}*/
return rs.next();//如果有下一行,则返回true
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCUtils.close(rs,pstmt,conn);
}
return false;
}
}
public class JDBCDemo10 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt1 = null;
PreparedStatement pstmt2 = null;
try {
//1.获取连接
conn = JDBCUtils.getConnection();
//开启事务(若代码中有错则会进行回滚)
conn.setAutoCommit(false);
//2.定义sql
//2.1 张三 - 500
String sql1 = "update account set balance = balance - ? where id = ?";
//2.2 李四 + 500
String sql2 = "update account set balance = balance + ? where id = ?";
//3.获取执行sql对象
pstmt1 = conn.prepareStatement(sql1);
pstmt2 = conn.prepareStatement(sql2);
//4. 设置参数
pstmt1.setDouble(1,500);
pstmt1.setInt(2,1);
pstmt2.setDouble(1,500);
pstmt2.setInt(2,2);
//5.执行sql
pstmt1.executeUpdate();
pstmt2.executeUpdate();
//提交事务
conn.commit();
} catch (Exception e) {
//事务回滚
try {
if(conn != null) {
conn.rollback();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}finally {
JDBCUtils.close(pstmt1,conn);
JDBCUtils.close(pstmt2,null);
}
}
}
CREATE DATABASE students;
CREATE TABLE scores(
id INT PRIMARY KEY,
NAME VARCHAR(32) NOT NULL,
sex VARCHAR(1),
score DOUBLE(5,2)
);
INSERT INTO scores VALUES(201826501,'老王','男',88.2),(201826502,'老胡','男',99.3),(201826503,'老薛','男',100),(201826504,'老巴','女',89.3),(201826505,'老谢','女',95.6);
UPDATE scores SET score = score-5 WHERE sex='男';
SELECT * FROM scores WHERE id = 201826501;
package cn.work.demo.Jdbc;
import java.sql.*;
public class JdbcDemo01 {
public static void main(String[] args) {
//导入厂商jar包,复制包到新建文件夹lib,再add as Library
/*
mysql厂商的jar包在5版本后里的META-INF中已经注册驱动,可以不写
Class.forName("com.mysql.jdbc.Driver");
*/
Connection conn = null;
//获取数据库连接对象
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/students", "root", "123");
} catch (SQLException e) {
e.printStackTrace();
}
//查询全部
Query query = new Query(conn);
//修改分数
UpdateScores update = new UpdateScores(conn);
//查询单一人员信息
QueryOne onePerson = new QueryOne(conn);
//主菜单
Menu menu = new Menu(query,update,onePerson);
//关闭连接
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
package cn.work.demo.Jdbc;
import java.util.Scanner;
public class Menu {
private boolean flag = true;
private Scanner scanner =null;
public Menu(Query query, UpdateScores update, QueryOne onePerson) {
System.out.println("
JDBC实验
");
System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *" );
System.out.println(" 1.查询全部人员信息
");
System.out.println(" 2.修改分数男生-5女生+3
");
System.out.println(" 3.查询某人信息
");
System.out.println(" 4.退出
");
System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *" );
scanner = new Scanner(System.in);
//菜单
do{
System.out.println("请输入要选择的数字:");
int command = scanner.nextInt();
switch (command){
case 1:
query.execute();
break;
case 2:
update.execute();
break;
case 3:
onePerson.execute();
break;
case 4:
flag=false;
break;
default:
System.out.println("输入错误请重新输入");
break;
}
}while (flag);
}
}
package cn.work.demo.Jdbc;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Query {
private Statement statement=null;
private Connection conn;
private ResultSet count=null;
public Query( Connection conn) {
this.conn = conn;
}
public void execute() {
try {
//定义查询SQL语句,语句不加分号
String sql = " select * from scores ";
//获取执行sql的对象,Connection里的方法返回Statement
statement = conn.createStatement();
//执行SQL,返回ResultSet
count = statement.executeQuery(sql);
//处理结果,打印在控制台
//先让光标移动一行,进入数据区域进行打印输出
while (count.next()) {
System.out.print(count.getInt(1) + "-----");
System.out.print(count.getString(2) + "-----");
System.out.print(count.getString(3) + "-----");
System.out.println(count.getDouble(4));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
//释放资源
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (count != null) {
try {
count.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
package cn.work.demo.Jdbc;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
public class UpdateScores {
private Statement statement=null;
private Connection conn;
public UpdateScores(Connection conn) {
this.conn = conn;
}
public void execute() {
try {
//定义查询SQL语句
String sqlMen = "UPDATE scores SET score = score-5 WHERE sex='男'";
String sqlWonmen = "UPDATE scores SET score = score+3 WHERE sex='女'";
//创建一个 Statement 对象来将 SQL 语句发送到数据库
statement = conn.createStatement();
//执行SQL
statement.executeUpdate(sqlMen);
statement.executeUpdate(sqlWonmen);
} catch (SQLException e) {
e.printStackTrace();
} finally {
//释放资源
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
package cn.work.demo.Jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class QueryOne {
//PreparedStatement动态参数
private PreparedStatement pstatement=null;
private Connection conn;
private ResultSet count=null;
private Scanner scanner;
public QueryOne(Connection conn) {
scanner = new Scanner(System.in);
this.conn = conn;
}
public void execute() {
try {
System.out.println("请输入要查询学号:");
int id = Integer.parseInt(scanner.next());
String sql = "SELECT * FROM scores WHERE id = ?";
//获取SQL执行的对象
pstatement = conn.prepareStatement(sql);
//传递动态参数
pstatement.setInt(1,id);
//执行SQL
count = pstatement.executeQuery();
if (count.next()){
System.out.print(count.getInt(1) + "-----");
System.out.print(count.getString(2) + "-----");
System.out.print(count.getString(3) + "-----");
System.out.println(count.getDouble(4));
} else
System.out.println("学号未找到!!!");
} catch (SQLException e) {
e.printStackTrace();
} finally {
//释放资源
if (pstatement != null) {
try {
pstatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
//1.创建数据库连接池对象,不传参数则使用默认配置
DataSource ds = new ComboPooledDataSource();
//2. 获取连接对象
Connection conn = ds.getConnection();
//3.加载配置文件
Properties pro = new Properties();
//当前类的资源路径,找到配置文件,返回字节输入流
InputStream is = DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties");
//加载
pro.load(is);
//4.获取连接池对象
DataSource ds = DruidDataSourceFactory.createDataSource(pro);
//5.获取连接
Connection conn = ds.getConnection();
```java
public class JDBCUtils {
//1.定义成员变量 DataSource
private static DataSource ds ;
//静态代码块初始化
static{
try {
//1.加载配置文件
Properties pro = new Properties();
pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
//2.获取DataSource
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取连接
*/
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
/**
* 释放资源
*/
public static void close(Statement stmt,Connection conn){
/* if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();//归还连接
} catch (SQLException e) {
e.printStackTrace();
}
}*/
//调用下面方法,简化书写
close(null,stmt,conn);
}
public static void close(ResultSet rs , Statement stmt, Connection conn){
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();//归还连接
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 获取连接池方法
*/
public static DataSource getDataSource(){
return ds;
}
}
```
Spring框架对JDBC的简单封装。提供了一个JDBCTemplate对象简化JDBC的开发
代码:
import cn.itcast.domain.Emp;
import cn.itcast.utils.JDBCUtils;
import org.junit.Test;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
public class JdbcTemplateDemo2 {
//Junit单元测试,可以让方法独立执行
//1. 获取JDBCTemplate对象
private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
/**
* 1. 修改1号数据的 salary 为 10000
*/
@Test
public void test1(){
//2. 定义sql
String sql = "update emp set salary = 10000 where id = 1001";
//3. 执行sql
int count = template.update(sql);
System.out.println(count);
}
/**
* 2. 添加一条记录
*/
@Test
public void test2(){
String sql = "insert into emp(id,ename,dept_id) values(?,?,?)";
int count = template.update(sql, 1015, "郭靖", 10);
System.out.println(count);
}
/**
* 3.删除刚才添加的记录
*/
@Test
public void test3(){
String sql = "delete from emp where id = ?";
int count = template.update(sql, 1015);
System.out.println(count);
}
/**
* 4.查询id为1001的记录,将其封装为Map集合
* 注意:这个方法查询的结果集长度只能是1
*/
@Test
public void test4(){
String sql = "select * from emp where id = ? or id = ?";
Map<String, Object> map = template.queryForMap(sql, 1001,1002);
System.out.println(map);
//{id=1001, ename=孙悟空, job_id=4, mgr=1004, joindate=2000-12-17, salary=10000.00, bonus=null, dept_id=20}
}
/**
* 5. 查询所有记录,将其封装为List
*/
@Test
public void test5(){
String sql = "select * from emp";
List<Map<String, Object>> list = template.queryForList(sql);
for (Map<String, Object> stringObjectMap : list) {
System.out.println(stringObjectMap);
}
}
/**
* 6. 查询所有记录,将其封装为Emp对象的List集合
*/
@Test
public void test6(){
String sql = "select * from emp";
List<Emp> list = template.query(sql, new RowMapper<Emp>() {
@Override
public Emp mapRow(ResultSet rs, int i) throws SQLException {
Emp emp = new Emp();
int id = rs.getInt("id");
String ename = rs.getString("ename");
int job_id = rs.getInt("job_id");
int mgr = rs.getInt("mgr");
Date joindate = rs.getDate("joindate");
double salary = rs.getDouble("salary");
double bonus = rs.getDouble("bonus");
int dept_id = rs.getInt("dept_id");
emp.setId(id);
emp.setEname(ename);
emp.setJob_id(job_id);
emp.setMgr(mgr);
emp.setJoindate(joindate);
emp.setSalary(salary);
emp.setBonus(bonus);
emp.setDept_id(dept_id);
return emp;
}
});
for (Emp emp : list) {
System.out.println(emp);
}
}
/**
* 6. 查询所有记录,将其封装为Emp对象的List集合
*/
@Test
public void test6_2(){
String sql = "select * from emp";
List<Emp> list = template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class));
for (Emp emp : list) {
System.out.println(emp);
}
}
/**
* 7. 查询总记录数
*/
@Test
public void test7(){
String sql = "select count(id) from emp";
Long total = template.queryForObject(sql, Long.class);
System.out.println(total);
}
}
初识JDBC
标签:rman 登录 数据区 actor read 定义 net 详解 int()
热心网友 时间:2022-05-03 04:08
第一阶段:小型桌面应用开发热心网友 时间:2022-05-03 05:26
尚学堂的java课程主要分为三个阶段:第一阶段:小型桌面应用开发第二阶段:中小型网站应用开发第三阶段:软件工程工业实践数据库(Oracle数据库管理及开发)、UI开发(WEB页面开发基础、XML、Ajax)、JAVAEE组件开发(jsp、servlet、jdbc)、框架技术(struts2.0、hibernate、spring、springMVC、mybatis)热心网友 时间:2022-05-03 07:01
首先学J2SE 也就是java标准 学习基本的语法 变量 然后接触集合 接口 线程 和图形界面 操作数据库 socket编程(网络编程) J2SE也就完事了