留下JDBC的代码以备后用
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class ConnUtil {
private static String driver;
private static String url;
private static String user;
private static String password;
static{
driver = "com.mysql.jdbc.Driver"; //驱动包名
url = " "jdbc:mysql:// IP :3306/zjgj" "; //ssh代表数据库名
user = " "; //数据库用户名密码
password = " ";
}
/**
* 获取连接
* */
public static Connection getConnection() throws Exception {
Class.forName(driver);//加载mysql的驱动类
return DriverManager.getConnection(url, user, password);
}
/**
* 释放资源
* */
public static void close(ResultSet rs, PreparedStatement pstmt ,Connection conn){
try {
if(rs!=null){
rs.close();
}
if(pstmt!=null){
pstmt.close();
}
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
System.out.println("JDBC释放资源出错");
}
}
}
添加数据
public void add(Zsyh zsyh) {
Connection conn = null;
PreparedStatement ptmt = null;
try {
conn = ConnUtil.getConnection();
//,last_price
String sql = "insert into price_data (item_code ,data_source,data_time,get_time,bid_price,ask_price) values (?,?,?,?,?,?)";
//ptmt= conn.prepareStatement(sql);
ptmt = conn.prepareStatement(sql);
ptmt.setString(1, zsyh.getItemCode());
ptmt.setString(2, zsyh.getDataSource());
ptmt.setTimestamp(3, zsyh.getDataTime());
ptmt.setTimestamp(4, zsyh.getGetTime());
ptmt.setDouble(5, zsyh.getBidPrice());
ptmt.setDouble(6, zsyh.getAskPrice());
// ptmt.setDouble(7, zsyh.getLastPrice());
int num = ptmt.executeUpdate();
System.out.println(zsyh.getGetTime()+" "+zsyh.getItemCode()+" 买入价: "+zsyh.getBidPrice()+" 卖出价: "+zsyh.getAskPrice());
System.out.println("成功插入"+sql);
//5如果有结果集处理结果集
} catch (Exception e) {
try {
Thread.sleep(2000);
System.out.println("添加数据到数据库出错");
} catch (Exception e1) {
}
} finally{
ConnUtil.close(null, ptmt, conn);
}
}