另:准备工作
电脑安装MySQL,安装MySQL可视化操作工具Workbench,创建好数据库。
一:连接数据库
--1--导入mysql相关jar包 :mysql-connector-jar(手动导包过程在另一文章)
--2--加载驱动
--3--通过Connection类,填写待连接数据库的基本信息
package jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; /** * Created by Seadragon on 2019-12-26. */ public class JdbcConnect { public static void main(String[] args) throws ClassNotFoundException { Connection connection = null; Statement statement = null; try { //初始化驱动,加载驱动 Class.forName("com.mysql.jdbc.Driver"); //Connection对象的连接,填写待连接数据库的信息。连接相关数据库 connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/ksea?characterEncoding=UTF-8", "root","root"); System.out.println("连接成功:"+connection.toString()); //创建sql语句相关对象 Statement statement = connection.createStatement(); System.out.println("获取sql语句对象:"+statement); //准备相关sql语句 //自增主键的位置用NULL代替即可 String sql = "INSERT INTO hero VALUES (NULL ,‘男枪‘, 3150)"; int i = 100; while (i!=0) { statement.execute(sql); i--; } } catch (SQLException e) { e.printStackTrace(); }finally { //关闭连接,释放资源 //先关statement,再关Connection if(statement!=null){ try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection!=null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } System.out.println("关闭:"+statement+"----"+connection); } } }
二:数据库操作
Connection对象用于连接数据库
--1--调用方法为调用mysql驱动类,DriverManager.getConnection(url)
Statement对象用于对sql语句操作,
--1--创建:connection.createStatement
--2--执行:executeQuery()【执行查询,返回的是ResultSet对象】;execute【增删更新,可以通过getResultSet进行查询,返回的是Boolean】;executeUpdate【不可查询,返回数据是受影响的数据条数】
ps:sql语句中自增长用null代替即可
PreparedStatement为Statement的升级版,sql的语句可简写,预编译机制速度快,可以预防sql注入式攻击
--1--sql注入攻击:改变sql语句结构,例如:拼接 "sql"+"or 1=1",使得语句无限次执行
--2--PreparedStatement只可设置值,分为预编译和执行两个阶段,且不可改变sql结构,故能防御注入
package jdbc; import java.sql.*; /** * Created by Seadragon on 2019-12-26. */ public class JdbcPreparedStatemen { public static void main(String[] args) throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); Connection connection = null; Statement statement = null; String sql_preState = "insert into hero values(null,?,?)"; String sql_state = "insert into hero VALUES (null,"+"‘提莫‘,"+12+")"; //执行sql语句的两种方式 connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/ksea?","root","root"); statement = connection.createStatement(); PreparedStatement preparedStatement = connection.prepareStatement(sql_preState); statement.execute(sql_state); preparedStatement.setString(1,"提莫pre"); preparedStatement.setInt(2,1233); preparedStatement.execute(); } }
三:数据库元数据
即数据库名称,有哪些表等一些的基本数据,通过DatabaseMetaData对象获取,调用getMetaData方法
package jdbc; import java.sql.*; /** * Created by Seadragon on 2019-12-27. */ public class getMetaData { public static void main(String[] args) throws SQLException, ClassNotFoundException { Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/ksea?","root","root"); DatabaseMetaData databaseMetaData = connection.getMetaData(); System.out.println(databaseMetaData.getDatabaseProductName()); System.out.println(databaseMetaData.getDatabaseProductVersion()); } }
四:事务
即把几个sql语句的执行打包在一起,若全都成功执行才执行,若有一条失败则全都不执行。处理方法为关闭自动提交改为手动提交。
--1---
connection.setAutoCommit(false)
{sql}
connection.commit()
package jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; /** * Created by Seadragon on 2019-12-27. */ public class JdbcTransaction { public static void main(String[] args) throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/ksea?","root","root"); Statement statement = connection.createStatement(); connection.setAutoCommit(false); String sql = "insert into user values(NULL,"+"‘kkk‘,"+"‘12345‘"+")"; String sql_false = "insert into rrrr values(NULL,"+"‘kkk‘,"+"‘12345‘"+")"; statement.execute(sql); statement.execute(sql_false); connection.commit(); System.out.println("你是否要删除该数据"); } }
五:ORM
对象映射数据,即把数据库的每条数据与一对象映射,我愿理解为数据库在java中的封装
package jdbc; import hero.Hero; import jdbc.*; import java.security.PublicKey; import java.sql.*; /** * Created by Seadragon on 2019-12-27. */ public class JdbcORM { public static void main(String[] args) throws ClassNotFoundException, SQLException { Hero hero = get(3); Hero hero_add = new Hero("男枪",12); add(hero_add); delete("男枪"); update(1); System.out.println(hero.getName()+":"+hero.getPrice()); } public static Connection connectMysql() throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/ksea?","root","root"); return connection; } //ID查询 public static Hero get(int id) throws ClassNotFoundException, SQLException { Hero hero = null; Connection connection = connectMysql(); Statement statement = connection.createStatement(); String sql = "select * from hero where idHero = "+id; ResultSet resultSet = statement.executeQuery(sql); while (resultSet.next()){ hero = new Hero(); String name = resultSet.getString("name"); int price = resultSet.getInt("price"); hero.setName(name); hero.setPrice(price); } return hero; } //add方法 public static void add(Hero hero) throws ClassNotFoundException, SQLException { Connection connection = connectMysql(); String sql = "insert into hero values(null,?,?)"; PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1,hero.getName()); preparedStatement.setInt(2,hero.getPrice()); preparedStatement.execute(); } //delete方法 public static void delete(String heroname) throws SQLException, ClassNotFoundException { Connection connection = connectMysql(); String sql = "DELETE FROM hero WHERE NAME = ?"; PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1,heroname); preparedStatement.execute(); } //update public static void update(int id) throws SQLException, ClassNotFoundException { Connection connection = connectMysql(); String sql = "UPDATE hero SET name = ?,price = ? WHERE idHero = ?"; PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1,"修改的英雄名称"); preparedStatement.setInt(2,1234); preparedStatement.setInt(3,id); preparedStatement.execute(); } }
六:连接池
减少创建数据库创建连接和关闭连接的时间,创建连接池,里面开启n条连接永不关闭。
若需要连接数据库,则往连接池中申请,若连接池有空闲连接,则给它;使用完连接后不直接关闭而是返还到连接池中处于空闲状态。
涉及多线程相关
package jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * Created by Seadragon on 2019-12-28. */ public class JdbcConnectionPool { List<Connection> connections = new ArrayList<Connection>(); int size; public JdbcConnectionPool(int size) throws SQLException, ClassNotFoundException { this.size=size; init(); } public void init() throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); for (int i = 0;i<size;i++) { Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/ksea?", "root", "root"); connections.add(connection); } } public synchronized Connection getConnection() throws InterruptedException { while (connections.isEmpty()){ this.wait(); } Connection connection = connections.remove(0); return connection; } public synchronized void returnConnection(Connection connection){ connections.add(connection); this.notifyAll(); } }
原文:https://www.cnblogs.com/KSea/p/12095970.html