Jdbc 데이터 베 이 스 를 연결 하 는 두 가지 방식

2665 단어 데이터 뱅 크
jdbc 링크 데이터베이스
   1.  Statement,  Statement  ,       ,             or          。
/*
 *         
 * */
package com.exp2;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class Test1 {
    public static void main(String[] args) throws Exception {
        Class.forName("com.mysql.jdbc.Driver");

        String url = "jdbc:mysql://10.21.1.10:3306/oracle?useUnicode=true&characterEncoding=UTF-8";
        String user = "root";
        String pwd = "zhang";

        Connection conn = DriverManager.getConnection(url, user, pwd);

        Statement stmt = conn.createStatement();

        String sql = "select * from user";
        ResultSet rs = stmt.executeQuery(sql);

        List list = new ArrayList();
        while(rs.next()){
            int id = rs.getInt("id");
            String name = rs.getString("name");
            int age = rs.getInt("age");
            String money = rs.getString("money");
            String dept = rs.getString("dept");
            User u = new User(id, name, age, money, dept);
            list.add(u);
        }

        System.out.println(list);
    }
}
2.  PreparedStatement,  PreparedStatement  ,        ,             。
/*
 *    
 * */

package com.exp1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Test {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {

        Class.forName("com.mysql.jdbc.Driver");

        String url = "jdbc:mysql://10.21.1.10:3306/oracle?useUnicode=true&characterEncoding=UTF-8";
        String user = "root";
        String pwd = "zhang";

        Connection conn = DriverManager.getConnection(url, user, pwd);

        String sql = "select *from student where score > ? and age < ?";

        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setDouble(1, 60);
        ps.setInt(2, 20);


        ResultSet rs = ps.executeQuery();

        while(rs.next()){
            System.out.println(rs.getString("name")+"---"+rs.getInt("age")+"---"+rs.getDouble("score"));
        }

        rs.close();
        ps.close();
        conn.close();
    }
}
        ,           ,      。

좋은 웹페이지 즐겨찾기