1.注册加载一个Drvier驱动:
Class.forName("..........");
2.创建数据库连接
- String url="jdbc:oracle:thin:@172.16.0.6:1521:tangjl";
- String user="openlab";
- String password="open123";
- Connection Con=DriverManager.getConnection(url,user,password);
Jdbc:oracle:this:(协议)@xxx.xxx.xxx:xxx(ip地址及端口号):xxx(使用数据库名)
Mysql的url是jdbc:mysql://localhost:3306/test
3.获得一个statement对象(PreparedStatement)
- String sql="select * from a_yyy";
- Statement s=con.createStatment();
- PreparedStatement ps=con.prepareStatement(sql);
4.通过Statement执行sql语句:
Statement接口代表了一个数据库的状态,在向数据库发送相应的SQL语句时,都需要创建Statement接口或者PreparedStatement接口。在具体应用中,Statement主要用于操作不带参数(可以直接运行)的SQL语句,比如删除语句、添加或更新。
Sta.execute():适合任何语句
sta.executeQuery(sql):适合查询语句.返回一个查询结果集.
sta.executeUpdate(sql);适合增删改创建语句,返回值为影响记录的条数
5.获取结果集里面的数据
按照上面的步骤写,我相信写代码的时候思路会是很清晰的,速度也会提高不少。
下面是代码例子:
- package cn.university.util;
- import java.io.IOException;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Properties;
- import cn.university.bin.employee;
- import com.mysql.jdbc.Statement;
- public class JdbcUtil {
- public static Connection conn=null;
- public static Statement st=null;
- public static ResultSet rs=null;
- public static Properties config=new Properties();
- static {
- try {
- try {
- config.load(JdbcUtil.class.getClassLoader().getResourceAsStream("config.porpertise"));
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- //1.加载驱动:
- Class.forName(config.getProperty("driver"));
- } catch (ClassNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- //返回数据库的链接
- public static Connection getConnection() throws SQLException{
- //2.创建链接
- return DriverManager.getConnection(config.getProperty("url"),
- config.getProperty("username"), config.getProperty("password"));
- }
- public static void main (String args[]) throws Exception{
- conn=getConnection();
- //3.获取一个Statement的对象:
- st=(Statement) conn.createStatement();
- //通过Statement操作数据库:
- rs=st.executeQuery("select * from users");
- List<employee> s=new ArrayList<employee>();
- //5.从结构集获取数据
- while(rs.next()){
- employee e=new employee();
- e.setId(rs.getString("id"));
- e.setName(rs.getString("name"));
- e.setPassword(rs.getString("password"));
- e.setBirthday(rs.getDate("birthday"));
- e.setSalary(rs.getDouble("salary"));
- e.setDepartment_id(rs.getString("department"));
- s.add(e);
- // System.out.println(rs.getInt("id")+"\t"+rs.getString("name")+"\t"+rs.getString("password")+"\t"+rs.getDate("birthday")+"\t"+rs.getString("email"));
- }
- System.out.println("ID\t姓名\t密 码 \t出 生 日 期\t工资\t部门");
- Iterator<employee> it=s.iterator();
- while (it.hasNext()){
- employee e=it.next();
- System.out.println
- (e.getId()+"\t"+e.getName()+"\t"+
- e.getPassword()+"\t"+e.getBirthday()+"\t"+e.getSalary()+"\t"+e.getDepartment_id());
- }