package com.fd.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCDemo01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Connection conn = null;
try {
//加载驱动类
Class.forName("com.mysql.jdbc.Driver");
//建立连接
long start = System.currentTimeMillis();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/iot", "root", "root");
long end = System.currentTimeMillis();
System.out.println("end - start = " + (end - start) + "ms");
Statement state = conn.createStatement();
ResultSet result = state.executeQuery("select * from user");
while(result.next()) {
System.out.println(result.getInt(1) + " " + result.getString(2) + " " + result.getString(3));
}
result.close();
//createStatement 会有sql注入问题
//PreparedStatement 可以
PreparedStatement pStatement = conn.prepareStatement("delete from user where id = ?");
pStatement.setInt(1, 3);
pStatement.executeUpdate();
conn.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if(conn != null)
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}