今天用intellijIDEA写了个数据库连接,把步骤理清了,具体的大步骤如下:
1:Load a Driver;
调用Class.forName(“aaa”);
相当于NEW出了一个aaa实例。
2 : Connect to the DateBase;
API:
DriverManager.getConnection();
getConnection
public static Connection getConnection(String url,String user,String password)
throws SQLException试图建立到给定数据库 URL 的连接。DriverManager 试图从已注册的 JDBC 驱动程序集中选择一个适当的驱动程序。
参数:
url - jdbc:subprotocol:subname 形式的数据库 url
user - 数据库用户,连接是为该用户建立的
password - 用户的密码
返回:
到 URL 的连接
抛出:
SQLException - 如果发生数据库访问错误
3 : Execute the SQL
1:Connection.CreateStatement();
2:Statement.executeQuery();
3:Statement.executeUpdate();
4:Retrieve the result data;
1:循环遍历取得结果集while(rs.next());
5:show the result data;
1:讲数据库中的各种类型转化为java中的数据类型(getXXX)方法;
6:Close
close the resultset / close the statement/ close the connection
代码如下:
package com.test.heihei;
import java.sql.*;
/**
* Created with IntelliJ IDEA.
* User: Administrator
* Date: 15-8-6
* Time: 上午9:51
* To change this template use File | Settings | File Templates.
*/
public class JDBCtest {
public static void main(String[] args) throws Exception{
String driver = "com.mysql.jdbc.Driver";
// URL指向要访问的数据库名emp
String url = "jdbc:mysql://127.0.0.1:3306/emp";//数据库连接字符串
// MySQL配置时的用户名 和密码
String user = "root";
String password = "hai123";
// 加载驱动程序
//new出类的驱动对象实例。。在堆内存new出一个对象 com.mysql.jdbc.Drive
Class.forName(driver);
// 连接数据库 getConnection的三个参数。第一个为数据库连接字符串。
Connection conn = DriverManager.getConnection(url, user, password);
// 连续数据库 getConnection的三个参数。第一个为数据库连接字符串。
// 创建语句对象
//通过coon连接创建一个Statement(
if(!conn.isClosed())
System.out.println("Succeeded connecting to the Database!");
// statement用来执行SQL语句
Statement statement = conn.createStatement();
// 结果集 、 使用Statement里面的方法
ResultSet rs = statement.executeQuery( "select * from dept");
// executeQuery方法会返回一个结果集!ResultSet。rs就像一个游标与数据库的不太一样
//rs游标的指针指在记录的上面,把结果集循环遍历取结果集!
//游标的移动调用rs.next();
System.out.println("-----------------");
System.out.println("执行结果如下所示:");
System.out.println("-----------------");
System.out.println("部门号" + "\t" + "部门名"+"\t" +"部门经理"+"\t"+"联系电话");
System.out.println("-----------------");
while(rs.next()) {
//rs.getString("deptId");//把字段的内容当成字符串拿出来,不管里面是什么都当成字符串拿出来。
//拿到了还要再输出来!
System.out.println(rs.getString("deptId") + "\t" + rs.getString("deptName")+"\t"+ rs.getString("namager")+"\t"+ rs.getString("phone"));
}
rs.close();//先打开的后关闭。
statement.close();
conn.close();
}
}