JDBC开发入门

一、什么是JDBC

JDBC(Java DataBase Connectivity)就是java 数据库连接,说白了就是用java语言来操作数据库,原来我们操作数据库是在控制台使用SQL语句来操作数据库,JDBC是用Java语言向数据库发送SQL语句

连接数据库:

/**
		 * jdbc四大配置参数
		 * driverClassName:com.mysql.jdbc.Driver
		 * url:jdbc:mysql://localhost:3306/mydb1
		 * username:root
		 * password:123
		 */

二:通过JDBC实现增、删、改、查

1.增、删、改操作:

/*
			 * 对数据库做增删改操作
			 */
			//1.通过Connection获取Statement对象,他的功能就是向数据库发送sql语句
			Statement stm=cno.createStatement();
			String sql="insert into student values('2018','关羽','家里蹲',25)";
			String sql="update student set sname='猴子' where sno='2018' ";
			String sql="delete from student where sname='猴子'";
			int len=stm.executeUpdate(sql);//返回值是一个整数,代表影响了几行,可以发送DDL,DML
			System.out.println(len);

2.查询数据库:

/**
			 * 2.对数据库进行查询操作
			 */
			//1.通过Connection获取Statement对象
			Statement stm=cno.createStatement();
			//2.通过对象方法executeQuary向数据库发送查询语句
			String sql="select * from student";
			//3.获取Result对象,并解析Result
			ResultSet rs=stm.executeQuery(sql);
		    while(rs.next()) {//判断是否还有下一行
		    	String sno=rs.getString(1);//可以通过列编号获取,也可以通过列名获取
		    	String sname=rs.getString(2);
		    	String education=rs.getString(3);
		    	int sage=rs.getInt(4);
		    	System.out.println(sno+","+sname+""+education+","+sage);
		    	
		    }

三、PreparedStatement

作用:可以防值SQL攻击
SQL攻击:

	/**
		 * Sql攻击
		 */
		String userName="a' or 'a' = 'a";
		String password="a' or 'a' = 'a";
		try {
			System.out.println(login1(userName,password));
			System.out.println(login2(userName,password));
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

使用PreparedStatement防止SQL攻击:

Connection con=DriverManager.getConnection(url, username, password);
		//2.用Connection得到PrepareStateMent对象
		String sql="select * from user where username=? and password=?";
		PreparedStatement pstmt =con.prepareStatement(sql);
		pstmt.setString(1,userName);//给第一个问号赋值
		pstmt.setString(2,passWord);//给第二个问号赋值
		ResultSet rs=pstmt.executeQuery();
		return rs.next();

//?位置可以是任意位置

三、向数据库中存储和读取大数据文件如mp3文件

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.rowset.serial.SerialBlob;

import org.apache.commons.io.IOUtils;

public class Demo4 {
	/**
	 * 在mysql中保存mp3文件
	 * @param args
	 */
	public static void save() {
		/**
		 * 1.连接数据库
		 * 2.创建sql模板
		 * 3.给模板传入参数
		 * 4.上传数据
		 */
		try {
			Connection con=JdbcUtils.getConnection();
			String sql="insert into tab_bin values(?,?,?)";
			PreparedStatement pstmt=con.prepareStatement(sql);
			pstmt.setInt(1, 2);
			pstmt.setString(2, "我们之间.mp3");
			//将文件变成一个字节数组
			byte []bytes=IOUtils.toByteArray(new FileInputStream("D:\\学习\\javaEE\\我们.mp3"));
			//通过SerialBlob得到一个Blob
			Blob blob=new SerialBlob(bytes);
			pstmt.setBlob(3,blob);
			pstmt.executeUpdate();
			System.out.println("存储成功");
			pstmt.close();
			con.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 在数据库中读取mp3文件
	 */
	public static void read() {
		/**
		 * 1.连接数据库
		 * 2.创建sql模板
		 * 3.读取blob中的数据
		 */
	   try {
		Connection con=JdbcUtils.getConnection();
		String sql="select * from tab_bin where id=?";
		PreparedStatement pstmt=con.prepareStatement(sql);
		pstmt.setInt(1, 2);
		ResultSet rs=pstmt.executeQuery();
		if(rs.next()) {
			Blob blob=rs.getBlob("data");
			InputStream in=blob.getBinaryStream();
			FileOutputStream out=new FileOutputStream("D:\\学习\\javaEE\\2.mp3");
			IOUtils.copy(in,out);
		}
		pstmt.close();
		con.close();
		System.out.println("读取成功");
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	   
	}
    
	public static void main(String[] args) {
    	//save();
		read();
		
	}

}

五、PreparedStatement实现批处理功能

可以大大加快数据库存取的效率
配置:在数据库url后面添加rewriteBatchedStatements=true参数
代码实现:

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Demo5 {
	public static void main(String[] args) {
		/*
		 * 向数据库成批发送语句
		 * 1.连接数据库
		 * 2.得到PreparedStment对象
		 * 3.获取sql模板
		 * 4.存储记录
		 * 5.发送记录
		 */
		try {
			Connection con=JdbcUtils.getConnection();
			String sql="insert into stu values(?,?,?)";
			PreparedStatement pstmt =con.prepareStatement(sql);
			for(int i=0;i<10000;i++) {
				pstmt.setInt(1, i);
				pstmt.setString(2, "stu_"+i);
				pstmt.setInt(3, i);
				pstmt.addBatch();//添加批这一组参数就添加在批里了
			}
			long start =System.currentTimeMillis();
			pstmt.executeBatch();//执行批
			long end =System.currentTimeMillis();
			System.out.println(end-start);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}

原创文章 114 获赞 84 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_44867340/article/details/105605604