关于java用JDBC连接数据库的代码

留下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);
        }
    }

转载于:https://my.oschina.net/u/3060369/blog/817563

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值