1. 程式人生 > 其它 >Jdbc連線資料庫的兩種方式

Jdbc連線資料庫的兩種方式

技術標籤:Java工具mysqlmysqljdbc資料庫sql

1、Statement

public class JdbcTest {
    public static void main(String[] args) throws Exception {
        String url = "jdbc:mysql://ip:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password =
"密碼"; // 1、載入驅動 Class.forName("com.mysql.jdbc.Driver"); // 2、連線資料庫 Connection connection = DriverManager.getConnection(url, username, password); // 3、向資料庫傳送sql Statement statement = connection.createStatement(); // 4、編寫sql // String sql = "select * from users";
// String sql = "delete from users where id = 2"; String sql = "INSERT INTO users VALUES (7, '王進', '123', '[email protected]', '1999-2-7');"; // 5、執行sql // ResultSet resultSet = statement.executeQuery(sql); // while (resultSet.next()) { // System.out.println("id=" + resultSet.getObject("id"));
// System.out.println("name=" + resultSet.getObject("name")); // System.out.println("password=" + resultSet.getObject("password")); // System.out.println("email=" + resultSet.getObject("email")); // System.out.println("birthday=" + resultSet.getObject("birthday")); // } int i = statement.executeUpdate(sql); // 返回受影響的行數 System.out.println(i); // 6、關閉連線 // resultSet.close(); statement.close(); connection.close(); } }

2、PreparedStatement(預編譯)

public class JdbcTest2 {
    public static void main(String[] args) throws Exception {
        String url = "jdbc:mysql://ip:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "密碼";

        // 1、載入驅動
        Class.forName("com.mysql.jdbc.Driver");

        // 2、連線資料庫
        Connection connection = DriverManager.getConnection(url, username, password);

        // 3、編寫sql
        String sql = "insert into users(id, name, password, email, birthday) values (?, ?, ?, ?, ?)";

        // 4、預編譯
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        // 賦值
        preparedStatement.setInt(1, 8);
        preparedStatement.setString(2, "狂神");
        preparedStatement.setString(3, "123");
        preparedStatement.setString(4, "[email protected]");
        preparedStatement.setDate(5, new Date(new java.util.Date().getTime()));

        // 5、執行sql
        int i = preparedStatement.executeUpdate();
        System.out.println(i);

        // 6、關閉連線
        preparedStatement.close();
        connection.close();

    }
}