再次熟悉jdbc连接mysql
闲来无事想探究一下jdbc
1.首先准备工作。我们要下载jdbc驱动包mysql-connector-java-5.1.7-bin.jar。其他的暂时先不用,这个包的下载地址:http://pan.baidu.com/s/1c2jYKBu
2.开始新建项目目录如下
3.编写ConnectDatebse.java
package com.wx.test; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import com.mysql.jdbc.Connection; import com.mysql.jdbc.PreparedStatement; import com.mysql.jdbc.Statement; public class ConnectDatebase { public static void main(String[] args) throws SQLException { // 1.加载jdbc驱动 try { Class.forName("com.mysql.jdbc.Driver"); } catch (Exception e) { System.out.println("没有找到jdbc驱动类"); } // 成功加载后,回将driver类的实例注册到DriverManager类中 // 2.提供jdbc的连接url String url = "jdbc:mysql://localhost:3306/spring"; String username = "root"; String password = "1111"; Connection conn = null; String sql = "select * from user"; try { conn = (Connection) DriverManager.getConnection(url, username, password); } catch (Exception e) { System.out.println("数据库连接失败"); e.printStackTrace(); } //4创建一个statement /*要执行sql语句必须获得statement实例,statement实例分为以下3种类型。 * * 1.执行静态sql语句,通常通过statement实例实现 * 2.执行动态sql语句,通常用preparedstatement实例实现 * 3.执行数据库存储过程,通常通过callablestatement实例 * */ Statement stmt = (Statement) conn.createStatement(); PreparedStatement pstmt = (PreparedStatement) conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery("select * from user"); while(rs.next()){ int id = rs.getInt("id"); int id2 = rs.getInt(1);//这种方法貌似比较高效,这里的数字是从1开始的 String name = rs.getString("username"); System.out.println("id:"+id+"id2:"+id2+"name:"+name); } rs.close(); stmt.close(); pstmt.close(); } }
4.运行结果
id:2id2:2name:zhanglei
id:3id2:3name:"ceshi"
id:8id2:8name:嘿嘿
id:9id2:9name:哈哈34
id:12id2:12name:wx