Connection 连接类
package com.lchh.utils;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
import org.junit.Test;
import com.lchh.jdbc.ConnectionTest;
public class JdbcUtils {
@Test
public static Connection connectionUtil() throws Exception {
InputStream is = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(is);
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
String user = properties.getProperty("user");
String password = properties.getProperty("password");
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, user, password);
return connection;
}
}
PreparedStatement 预编译类
package com.lchh.jdbc;
import org.junit.Test;
import com.lchh.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
public class PreparedStatementTest {
@Test
public void insertTest() {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = JdbcUtils.connectionUtil();
String sqlInsertString = "insert into user (name,password,birth)values(?,?,?)";
preparedStatement = connection.prepareStatement(sqlInsertString);
preparedStatement.setString(1, "lchh");
preparedStatement.setString(2, "123456");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date parse = sdf.parse("1009-05-20");
preparedStatement.setDate(3, new Date(parse.getTime()));
preparedStatement.execute();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(preparedStatement!=null) {
preparedStatement.close();
}
if(connection!=null) {
connection.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}