• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
小小慧
博客园    首页    新随笔    联系   管理    订阅  订阅
用JDBC访问MySQL
/*
 在数据库中创建一个Employee的类
 create table Employee( id int primary key, name varchar(20), age int);
 */
import java.sql.*;
public class JDBCTest {
    public static void main(String[] args){
        String user="user1";
        String passwd="pwd1";
        String utl="jdbc:mysql://localhost:3306/Test";
        String driver="com.mysql.jdbc.Driver";
        Connection con=null;
        Statement stmt=null;
        ResultSet rs=null;
        try{
            try {
                Class.forName(driver);
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            con=DriverManager.getConnection(utl,user,passwd);
            stmt=con.createStatement();
            stmt.execute("insert into Employee values(1,'James1',25)");
            stmt.execute("insert into Employee values(2,'James2',26)");
            rs=stmt.executeQuery("select * from Empolyee");//访问结果集SQL对象
            while(rs.next()){
                System.out.println(rs.getInt(1)+""+rs.getString(2)+""+rs.getInt(3));
            }        
        }
        catch(SQLException e1){
            e1.printStackTrace();
            }finally{
                try{
                    if(rs!=null) rs.close();
                    if(stmt!=null) stmt.close();
                    if(con!=null) con.close();
                }catch(SQLException e){
                    System.out.println(e.getMessage());
                }
            }
    }

}

操作步骤

  1. 加载JDBC驱动器,将JDBC驱动加载到classpath中。
  2. 加载JDBC驱动,并将其注册到DriverManager中。一般使用反射机制class.forName(String driverName)
  3. 建立数据库连接,取得Connection对象。一般通过DriverManager.getConnection(url,username,passwd)方法实现,其中url表示连接数据库的字符串,uaername表示连接数据库的用户名,passwd表示连接数据库的密码。
  4. 建立Statement对象或PrepareStatement对象。
  5. 执行SQL语句。
  6. 访问结构集ResultSet对象。
  7. 依次访问ResultSet、Statement、PreparedStatement、Connection对象关闭,释放掉所占用的资源。
posted on 2016-08-28 11:54  小小慧  阅读(331)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3