一个完整的Mysql的JDBC连接

本文提供了一个使用 Java 进行数据库操作的简单示例,通过连接 MySQL 数据库并执行 SQL 查询语句来展示基本的 JDBC 使用流程。
  1. import java.sql.Connection;   
  2. import java.sql.DriverManager;   
  3. import java.sql.ResultSet;   
  4. import java.sql.SQLException;   
  5. import java.sql.Statement;   
  6.   
  7. public class TestJDBC {   
  8.   
  9.     public static void main(String[] args) {   
  10.         Connection conn = null;   
  11.         Statement stat = null;   
  12.         ResultSet rs = null;   
  13.   
  14.         try {   
  15.             //两种方式   
  16.             Class.forName("com.mysql.jdbc.Driver");   
  17.             //new com.mysql.jdbc.Driver();   
  18.             //连接数据库   
  19.             conn = DriverManager   
  20.                     .getConnection("jdbc:mysql://localhost/student?user=root&password=root");   
  21.             //创建一个Statement实例   
  22.             stat = conn.createStatement();   
  23.             //执行一些静态的SQL语句   
  24.             rs = stat.executeQuery("select * from c");   
  25.             System.out.println("id - name");   
  26.             while (rs.next()) {   
  27.                 System.out.print(rs.getInt("id"));   
  28.                 System.out.print(" - ");   
  29.                 System.out.print(rs.getString("name"));   
  30.                 System.out.println();   
  31.             }   
  32.         } catch (ClassNotFoundException e) {   
  33.             e.printStackTrace();   
  34.         } catch (SQLException e) {   
  35.             e.printStackTrace();   
  36.         } finally {   
  37.             try {   
  38.                 if (null != rs) {   
  39.                     rs.close();   
  40.                     rs = null;   
  41.                 }   
  42.                 if (null != stat) {   
  43.                     stat.close();   
  44.                     stat = null;   
  45.                 }   
  46.                 if (null != conn) {   
  47.                     conn.close();   
  48.                     conn = null;   
  49.                 }   
  50.             } catch (SQLException e) {   
  51.                 e.printStackTrace();   
  52.             }   
  53.         }   
  54.     }   
  55. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值