Java:使用JDBC连接

java获取JDBC连接:

import java.sql.Connection;
import java.sql.DriverManager;

public class Main {

    public static void main(String[] args) throws Exception {
        // 数据库相关信息,其中url格式为:协议:子协议:数据库标识
        // 协议:在JDBC中总是以jdbc开始
        // 子协议:是桥连接的驱动程序或是数据库管理系统名称。
        // 数据库标识:标记找到数据库来源的地址与连接端口和数据库名。
        String oracle_url = "jdbc:oracle:thin:@10.10.10.10:1521:orcl";
        String mysql_url = "jdbc:mysql://10.10.10.10:3306/data?useUnicode=true&characterEncoding=utf-8";
        String user = "root";
        String password = "123456";

        // 为DriverManager获取数据库连接而加载驱动,其中驱动程序有多种如:
        String oracle_driver = "oracle.jdbc.driver.OracleDriver"; // 加载此驱动需要ojdbc14.jar
        String mysql_driver = "com.mysql.jdbc.Driver"; // 加载此驱动需要mysql-connector-java-5.1.38-bin.jar
        Class.forName(oracle_driver);
        // 获取数据库连接
        Connection conn = DriverManager.getConnection(oracle_url, user, password);
    }

}

例子:查询mysql数据库(需要包mysql-connector-java-5.1.38-bin.jar)

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

public class TestA {
    public static void main(String[] args) throws Exception {
        MysqlDataSource dataSource = new MysqlDataSource();
        dataSource.setUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setUser("root");
        dataSource.setPassword("123456a?");

        Connection conn = dataSource.getConnection();
        PreparedStatement stmt = conn.prepareStatement("select * from user where id in (? , ?)");
        stmt.setInt(1, 1000);
        stmt.setInt(2, 1001);
        // statement is "select * from user where id in (1000 , 1001)"
        ResultSet rs = stmt.executeQuery();

        Statement stmt1 = conn.createStatement();
        ResultSet rs1 = stmt1.executeQuery("select * from map");

        while (rs.next() && rs1.next()) {
            String name = rs.getString("name");
            int key = rs1.getInt("key");
            System.out.println(name + key);
        }

        rs.close();
        stmt.close();
        rs1.close();
        stmt1.close();
        conn.close();
    }
}

将rs结果转换为List

ResultSetMetaData md = rs.getMetaData(); //得到结果集(rs)的结构信息,比如字段数、字段名等   
int columnCount = md.getColumnCount(); //返回此 ResultSet 对象中的列数   
while (rs.next()) {   
    Map<String,Object> rowData = new HashMap<String,Object>(columnCount);   
    for (int i = 1; i <= columnCount; i++) {   
        rowData.put(md.getColumnLabel(i), rs.getObject(i));   
    }   
    result.add(rowData);   
}
posted @ 2018-12-07 09:17  xuejianbest  阅读(409)  评论(0编辑  收藏  举报