- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- public class TestJDBC {
- public static void main(String[] args) {
- Connection conn = null;
- Statement stat = null;
- ResultSet rs = null;
- try {
- //两种方式
- Class.forName("com.mysql.jdbc.Driver");
- //new com.mysql.jdbc.Driver();
- //连接数据库
- conn = DriverManager
- .getConnection("jdbc:mysql://localhost/student?user=root&password=root");
- //创建一个Statement实例
- stat = conn.createStatement();
- //执行一些静态的SQL语句
- rs = stat.executeQuery("select * from c");
- System.out.println("id - name");
- while (rs.next()) {
- System.out.print(rs.getInt("id"));
- System.out.print(" - ");
- System.out.print(rs.getString("name"));
- System.out.println();
- }
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- try {
- if (null != rs) {
- rs.close();
- rs = null;
- }
- if (null != stat) {
- stat.close();
- stat = null;
- }
- if (null != conn) {
- conn.close();
- conn = null;
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- }
- }
一个完整的Mysql的JDBC连接
本文提供了一个使用 Java 进行数据库操作的简单示例,通过连接 MySQL 数据库并执行 SQL 查询语句来展示基本的 JDBC 使用流程。

被折叠的 条评论
为什么被折叠?



