JDBC_快速入门与JDBC各个类详解_DriverManager_注册驱动
JDBC_快速入门
步骤:
1.导入驱动jar包:mysql-connector-java-5.1.37-bin.jar
1.复制mysql-connector-java-5.1.37-bin.jar到项目的libs目录下
2.右键-->Add AS Libraty;
2.注册驱动
Class.forName("com.mysql.jdbc.Driver");
3.获取数据库的链接对象Connection
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/win", "root", "*******");
4.定义Sql
String sql = "update accont set balance = 500 where id = 2";
5.获取执行sql语句的对象Statement
Statement statement = connection.createStatement();
6.执行sql,接受返回结果
int i = statement.executeUpdate(sql);
7.处理结果
System.out.println(i);
8.释放资源
statement.close()
connection.close();
package CN.XueQiang.JDBC; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; /** * JDBC快速入门 */ public class JDBCDemo1 { public static void main(String[] args) throws Exception { //1. 导入驱动jar包 //2. 注册驱动 Class.forName("com.mysql.jdbc.Driver"); //3. 获取数据库连接对象 Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/win", "root", "njzyb555"); //4. 定义sql语句 String sql = "update accont set balance = 500 where id = 2"; //5. 获取执行sql的对象 Statement statement = connection.createStatement(); //6. 执行sql int i = statement.executeUpdate(sql); //7. 处理结果 System.out.println(i); //8. 释放资源 statement.close(); connection.close(); } }
JDBC各个类详解_DriverManager_注册驱动
详解各个对象:
1.DriverManager:驱动管理对象
功能:
1.注册驱动:告诉程序该使用哪一个数据库驱动jar
static void registerDriver(Driver driver) ;注册与给定的驱动程序 DriverManager 。
写代码使用: Class.forName("com.mysql.jdbc.Driver");
通过查看源代码发现:在com.jdbc.Driver类中存在静态代码块
static { try { DriverManager.registerDriver(new Driver()); } catch (SQLException var1) { throw new RuntimeException("Can't register driver!"); } }
注意:mysql5之后的驱动jar包可以省略注册驱动的步骤