JDBC:是官方定义大的一套 *** 作所有关系型数据库的规则,即接口
MySQL驱动jar包的下载方式:
地址:https://dev.mysql.com/downloads/
选择platform independent下载
JDBC使用步骤:
1.导入驱动jar包:复制到项目下的libs目录下,并且Add As Library
2.注册驱动
3.获取数据库连接对象Connection
4.定义sql
5.获取执行sql语句的对象statement
6.执行sql,接收返回结果
7.处理结果
8.释放资源
给数据表插入一条数据:
package test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class jdbcdem2 { public static void main(String[] args) { Statement stmt = null; Connection conn = null; try { //1.注册驱动 Class.forName("com.mysql.cj.jdbc.Driver"); //2.定义sql String sql = "insert into student values('zdbc','zdbc')"; //3.获取Connection对象 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/live","root","1234"); //4.获取执行sql的对象 stmt = conn.createStatement(); //5.执行sql int count = stmt.executeUpdate(sql); //6.处理结果 System.out.println(count); if(count>0){ System.out.println("添加成功"); } else { System.out.println("添加失败"); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException throwables) { throwables.printStackTrace(); }finally { //8.释放资源 if(stmt!=null){ try { stmt.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if(conn!=null){ try { conn.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } } }
查询数据:
package test; import java.sql.*; public class jdbcdem3 { public static void main(String[] args) { Statement stmt = null; Connection conn = null; ResultSet rs =null; try { //1.注册驱动 Class.forName("com.mysql.cj.jdbc.Driver"); //2.定义sql String sql = "select * from student"; //3.获取Connection对象 conn = DriverManager.getConnection("jdbc:mysql:///live","root","1234"); //4.获取执行sql的对象 stmt = conn.createStatement(); //5.执行sql rs = stmt.executeQuery(sql); //6.处理结果 while (rs.next()){ int id = rs.getInt("id"); String name = rs.getString("num"); String pass = rs.getString("pass"); System.out.println(name+'-'+pass); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException throwables) { throwables.printStackTrace(); }finally { //8.释放资源 if(rs!=null){ try { rs.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if(stmt!=null){ try { stmt.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if(conn!=null){ try { conn.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)