用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对象关闭,释放掉所占用的资源。
原文地址:https://www.cnblogs.com/xiaoxiaohui2015/p/5814676.html