jdbc database native operating procedures:
Step: Class.forName () to load the database driver is connected;
Step Two: DriverManager.getConnection () Gets a data connection object;
Step 3: obtaining SQL sql session object, there are two ways Statement, PreparedStatement;
Step Four: SQL execution result set, before executing SQL parameter value if the parameter value set the setXXX ();
Step Five: result set is closed, close the session, the connection is closed.
Code demonstrates
String URL = "jdbc:mysql://localhost:3306/database_name";
String USER = "root";
String PASS = "123";
Connection conn = null;
Statement stat = null;//这个不能防止sql注入,需要使用PreparedStatement
// 注册驱动
Class.forName("com.mysql.jdbc.Driver");
// 创建链接
conn = (Connection) DriverManager.getConnection(URL,USER,PASS);
// 执行查询
stat = conn.createStatement();
String sql = "SELECT * FROM table_name";
//结果集
ResultSet rs = stat.executeQuery(sql);
// 循环输出查询结果
while(rs.next()){
System.out.print(rs.getString("column_name"));
}
//释放资源
Long connected to the short connection
Long connection
called is connected to the presence of long duration sql transmitted to the database, typically 8 hours.
Short connection
so-called short connection is connected to the database after the operation is completed to release connection resources, but the next time they need to re-connect to the database. Such operation of the database more frequently, the performance is not very good.