JDBC编程步骤
Posted silentteller
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JDBC编程步骤相关的知识,希望对你有一定的参考价值。
加载驱动程序:
Class.forName(driverClass) //加载mysql驱动 Class.forName("com.mysql.jdbc.Driver") //加载Oracle驱动 Class.forName("oracle.jdbc.driver.OracleDriver")
获得数据库连接:
String url = "jdbc:mysql://localhost:3306/student"; String user = "root"; String password = "123456"; Connection connection = DriverManager.getConnection(url, user, password);
创建Statement对象:
Statement statement = connection.createStatement();
例子:
package com.silentteller.test; import java.sql.*; public class Test { public static void main(String[] args) { try { //1.加载驱动程序 Class.forName("com.mysql.cj.jdbc.Driver"); //2. 获得数据库连接 String url = "jdbc:mysql://localhost:3306/student"; String user = "root"; String password = "123456"; Connection connection = DriverManager.getConnection(url, user, password); System.out.println(connection); //3.操作数据库,实现增删改查 Statement statement = connection.createStatement(); String sql = "select * from student"; ResultSet rs = statement.executeQuery(sql); //如果有数据,rs.next()返回true while(rs.next()){ System.out.println(rs.getString("id") + rs.getString("student_id") + rs.getString("name") + rs.getInt("age") + rs.getString("sex") + rs.getString("birthday")); } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } }
以上是关于JDBC编程步骤的主要内容,如果未能解决你的问题,请参考以下文章
Java学习笔记8.1.2 初探JDBC - JDBC编程步骤