1.连接数据库
package com.atguigu.java;
import org.junit.Test;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class ConnectionTest {
@Test
public void testConnection1() throws SQLException {
//获取Driver实现类对象
Driver driver = new com.mysql.jdbc.Driver();
//jdbc:mysql:协议
//localhost:ip地址
//3306:默认mysql的端口号
//test:test数据库
String url="jdbc:mysql://localhost:3306/test";
//将用户名和密码封装在Properties中
Properties info = new Properties();
info.setProperty("user","root");
info.setProperty("password","wsf123");
Connection conn = driver.connect(url,info);
System.out.println(conn);
}
//方式2:对方式1的迭代:在如下的程序中不出现第三方api,使得程序具有更好的可移植性
@Test
public void testConnection2() throws Exception {
//1.获取Driver实现类对象,使用反射
Class> clazz = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
//2.提供要连接的数据库
String url = "jdbc:mysql://localhost:3306/test";
//3.提供连接需要的用户名和密码
Properties info = new Properties();
info.setProperty("user","root");
info.setProperty("password","wsf123");
//4.获取连接
Connection conn = driver.connect(url, info);
System.out.println(conn);
}
//方式3:使用DriverManager替换Driver
@Test
public void testConnection3() throws Exception{
//1.获取Driver实现类的对象
Class> clazz = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
//2.提供另外三个连接的基本信息
String url="jdbc:mysql://localhost:3306/test";
String user="root";
String password="wsf123";
//注册驱动
DriverManager.registerDriver(driver);
//获取连接
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
//方式4:使用DriverManager替换Driver
@Test
public void testConnection4() throws Exception{
//1.提供另外三个连接的基本信息
String url="jdbc:mysql://localhost:3306/test";
String user="root";
String password="wsf123";
//2.获取Driver实现类的对象
Class.forName("com.mysql.jdbc.Driver");
//获取连接
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
}
例子2
package com.atguigu3.preparedstatement.crud;
import com.atguigu3.util.JDBCUtils;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Properties;
public class PreparedStatementUpdateTest {
@Test
public void testCommonUpdate(){
//删除操作
// String sql = "delete from customers where id = ?";
// update(sql,3);
//修改操作
String sql = "update `order` set order_name = ? where order_id = ?";
update(sql,"DD","2");
}
//通用的增删改操作
public void update(String sql,Object ...args) {
Connection conn = null;
PreparedStatement ps = null;
try {
//sql中占位符的个数与可变形参的长度相同
//1.获取数据库的连接
conn = JDBCUtils.getConnection();
//2.预编译sql语句,返回
ps = conn.prepareStatement(sql);
//3.填充占位符
for(int i=0; i
例子3
CustomerForQuery
package com.atguigu3.preparedstatement.crud;
import com.atguigu3.bean.Customer;
import com.atguigu3.util.JDBCUtils;
import org.junit.Test;
import java.lang.reflect.Field;
import java.sql.*;
public class CustomerForQuery {
@Test
public void testQueryForCustomers(){
String sql = "select id,name,birth,email from customers where id = ?";
Customer customer = queryForCustomers(sql, 13);
System.out.println(customer);
sql="select name,email from customers where name = ?";
Customer customer1 = queryForCustomers(sql, "周杰伦");
System.out.println(customer1);
}
public Customer queryForCustomers(String sql,Object...args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
ps = conn.prepareStatement(sql);
for(int i=0; i
Customer
package com.atguigu3.bean;
import java.util.Date;
public class Customer {
private int id;
private String name;
private String email;
private Date birth;
public Customer() {
super();
}
public Customer(int id, String name, String email, Date birth) {
this.id = id;
this.name = name;
this.email = email;
this.birth = birth;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
@Override
public String toString() {
return "Customer{" +
"id=" + id +
", name='" + name + ''' +
", email='" + email + ''' +
", birth=" + birth +
'}';
}
}
例子4
package com.atguigu3.preparedstatement.crud;
import com.atguigu3.bean.Order;
import com.atguigu3.util.JDBCUtils;
import org.junit.Test;
import java.lang.reflect.Field;
import java.sql.*;
public class OrderForQuery {
@Test
public void testOrderForQuery(){
String sql = "select order_id orderId,order_name orderName,order_date orderDate from `order` where order_id=?";
Order order = orderForQuery(sql, 1);
System.out.println(order);
}
public Order orderForQuery(String sql,Object...args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
ps = conn.prepareStatement(sql);
for(int i=0; i
例子5
Customer
package com.atguigu3.bean;
import java.util.Date;
public class Customer {
private int id;
private String name;
private String email;
private Date birth;
public Customer() {
super();
}
public Customer(int id, String name, String email, Date birth) {
this.id = id;
this.name = name;
this.email = email;
this.birth = birth;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
@Override
public String toString() {
return "Customer{" +
"id=" + id +
", name='" + name + ''' +
", email='" + email + ''' +
", birth=" + birth +
'}';
}
}
Order
package com.atguigu3.bean;
import java.sql.Date;
public class Order {
private int orderId;
private String orderName;
private Date orderDate;
public Order() {
}
public Order(int orderId, String orderName, Date orderDate) {
this.orderId = orderId;
this.orderName = orderName;
this.orderDate = orderDate;
}
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
public String getOrderName() {
return orderName;
}
public void setOrderName(String orderName) {
this.orderName = orderName;
}
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
@Override
public String toString() {
return "Order{" +
"orderId=" + orderId +
", orderName='" + orderName + ''' +
", orderDate=" + orderDate +
'}';
}
}
PreparedStatementQueryTest
package com.atguigu3.preparedstatement.crud;
import com.atguigu3.bean.Customer;
import com.atguigu3.bean.Order;
import com.atguigu3.util.JDBCUtils;
import org.junit.Test;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetmetaData;
public class PreparedStatementQueryTest {
@Test
public void testGetInstance(){
String sql = "select id,name,email from customers where id = ?";
Customer customer = getInstance(Customer.class, sql, 12);
System.out.println(customer);
String sql1 = "select order_id orderId,order_name orderName from `order` where order_id=?";
Order order = getInstance(Order.class, sql1, 1);
System.out.println(order);
}
public T getInstance(Class clazz,String sql,Object...args){
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
ps = conn.prepareStatement(sql);
for(int i=0; i
例子6
package com.atguigu3.preparedstatement.crud;
import com.atguigu3.bean.Customer;
import com.atguigu3.bean.Order;
import com.atguigu3.util.JDBCUtils;
import org.junit.Test;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class PreparedStatementQueryTest {
@Test
public void testGetForList(){
String sql = "select id,name,email from customers where id";
List list = getForList(Customer.class, sql, 12);
list.forEach(System.out::println);
String sql1 = "select order_id orderId,order_name orderName from `order` where order_id";
List orderList = getForList(Order.class, sql1, 5);
orderList.forEach(System.out::println);
}
public List getForList(Class clazz, String sql, Object...args){
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
ps = conn.prepareStatement(sql);
for(int i=0; i list = new ArrayList<>();
while (rs.next()){
T t = clazz.getDeclaredConstructor().newInstance();
//处理结果集一行数据中的每一个列:給t對象指定的屬性賦值
for(int i=0; i T getInstance(Class clazz,String sql,Object...args){
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
ps = conn.prepareStatement(sql);
for(int i=0; i
例子7
package com.atguigu2.statement.crud;
import com.atguigu.statement.crud.User;
import com.atguigu3.util.JDBCUtils;
import org.junit.Test;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetmetaData;
import java.util.Scanner;
public class PreparedStatementTest {
@Test
public void testLogin() {
Scanner scan = new Scanner(System.in);
System.out.print("用户名:");
String user = scan.nextLine();
System.out.print("密 码:");
String password = scan.nextLine();
String sql = "SELECt user,password FROM user_table WHERe user = ? and password = ?";
User returnUser = getInstance(User.class,sql,user,password);
if (returnUser != null) {
System.out.println("登陆成功!");
} else {
System.out.println("用户名或密码错误!");
}
}
public T getInstance(Class clazz,String sql,Object...args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
ps = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1, args[i]);
}
rs = ps.executeQuery();
//获取结果集的原数据
ResultSetmetaData rsmd = rs.getmetaData();
//通过ResultSetmetaData获取结果集中的列数
int columnCount = rsmd.getColumnCount();
if (rs.next()) {
T t = clazz.getDeclaredConstructor().newInstance();
//处理结果集一行数据中的每一个列
for (int i = 0; i < columnCount; i++) {
//获取列值
Object columnValue = rs.getObject(i + 1);
//获取每个列的列名
String columnLabel = rsmd.getColumnLabel(i + 1);
//给cust对象指定的columnValue属性,赋值为value,通过反射
Field field = clazz.getDeclaredField(columnLabel);
field.setAccessible(true);
field.set(t, columnValue);
}
return t;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResource(conn, ps, rs);
}
return null;
}
}
例子8
package com.atguigu5.blob;
import com.atguigu3.util.JDBCUtils;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
public class BlobTest {
//向数据表customers中插入Blob类型的字段
@Test
public void testInsert(){
Connection conn = null;
PreparedStatement ps = null;
try {
conn = JDBCUtils.getConnection();
String sql = "insert into customers(name,email,birth,photo)values(?,?,?,?)";
ps = conn.prepareStatement(sql);
ps.setObject(1,"张宇豪");
ps.setObject(2,"zhang@qq.com");
ps.setObject(3,"1992-09-08");
FileInputStream is = new FileInputStream(new File("885.png"));
ps.setBlob(4,is);
ps.execute();
} catch (Exception e) {
e.printStackTrace();
}
JDBCUtils.closeResource(conn,ps);
}
}
例子9
package com.atguigu5.blob;
import com.atguigu3.bean.Customer;
import com.atguigu3.util.JDBCUtils;
import org.junit.Test;
import java.io.*;
import java.sql.*;
public class BlobTest {
//向数据表customers中插入Blob类型的字段
@Test
public void testInsert(){
Connection conn = null;
PreparedStatement ps = null;
try {
conn = JDBCUtils.getConnection();
String sql = "insert into customers(name,email,birth,photo)values(?,?,?,?)";
ps = conn.prepareStatement(sql);
ps.setObject(1,"张宇豪");
ps.setObject(2,"zhang@qq.com");
ps.setObject(3,"1992-09-08");
FileInputStream is = new FileInputStream(new File("885.png"));
ps.setBlob(4,is);
ps.execute();
} catch (Exception e) {
e.printStackTrace();
}
JDBCUtils.closeResource(conn,ps);
}
//查询数据表customers中Blob类型的字段
@Test
public void testQuery() throws Exception{
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
InputStream is=null;
FileOutputStream fos=null;
try {
conn = JDBCUtils.getConnection();
String sql = "select id,name,email,birth,photo from customers where id = ?";
ps = conn.prepareStatement(sql);
ps.setInt(1,30);
rs = ps.executeQuery();
if(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String email = rs.getString("email");
Date birth = rs.getDate("birth");
Customer cust = new Customer(id, name, email, birth);
System.out.println(cust);
//将Blob类型的字段下载下来,以文件的方式保存在本地
Blob photo = rs.getBlob("photo");
is = photo.getBinaryStream();
fos = new FileOutputStream("zhangyuhao.jpg");
byte[] buffer = new byte[1024];
int len;
while((len=is.read(buffer))!=-1){
fos.write(buffer,0,len);
}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(is!=null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(fos!=null)
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
JDBCUtils.closeResource(conn,ps,rs);
}
}
}