首页 > 代码库 > JDBC使用步骤

JDBC使用步骤

JDBC编程步骤

  • 加载驱动程序:Class.forName(driverClass)

  加载Mysql驱动:Class.forName("com.mysql.jdbc.Driver")

  加载Oracle驱动:Class.forName("oracle.jdbc.driver.OracleDriver")

  • 获取数据库连接:

  DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/DatabaseName","userName","password")

  • 创建Statement对象:

  conn.createStatement();

如下面的代码连接数据库:

 1 package com.gui; 2  3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.ResultSet; 6 import java.sql.Statement; 7  8 public class DBUtil { 9 10     private static final String URL = "jdbc:mysql://127.0.0.1:3306/imooc";11     private static final String USER = "root";12     private static final String PASSERWORD = "123";13 14     public static void main(String[] args) throws Exception {15 16         // 1.加载驱动程序17         Class.forName("com.mysql.jdbc.Driver");18 19         // 2.获取数据库的连接20         Connection conn = DriverManager.getConnection(URL, USER, PASSERWORD);21 22         // 3.通过数据库的连接操作数据库,实现增删改23         Statement stmt = conn.createStatement();24         ResultSet rs = stmt25                 .executeQuery("select user_name,age from imooc_goddess");26 27         while (rs.next()) {28             System.out.println(rs.getString("user_name") + ","29                     + rs.getString("age"));30 31         }32 33     }34 }

 

JDBC使用步骤