java - mysql连接

前置:

mysql-connector-java-x.x.xx-bin.jar (e.g. mysql-connector-java-5.1.26-bin.jar)


Get connection:

	public static Connection getConnection() {
		Connection conn = null;
        String url = "jdbc:mysql://192.168.22.250:3306/dbname?"
                + "user=test&password=111&useUnicode=true&characterEncoding=UTF8";
        try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(url);
        } catch (ClassNotFoundException e) {
        	e.printStackTrace();
        } catch (SQLException e) {
			e.printStackTrace();
		}
    	return conn;
	}

Update:

	public static void update(Connection conn, ResultSet rs, String updateField, Integer updateValue) {
		String sql = "update transform set " + updateField + " = ? where idcard = ? and mobile = ?";
        PreparedStatement ps = null;
        try {
			ps = conn.prepareStatement(sql);
	        ps.setInt(1,updateValue);
	        ps.setString(2,rs.getString(1));
	        ps.setString(3,rs.getString(2));
	        ps.executeUpdate();
        } catch (SQLException e) {
        	e.printStackTrace();
        }
	}

Select:

public static void main(String[] args) throws Exception {
		
		Connection conn = null;
        try {
        	conn = getConnection();
        	Statement stmt = conn.createStatement();
    		// table:transform
        	String sql2 = "select * from transform";
        	ResultSet rs2 = stmt.executeQuery(sql2);
    		while (rs2.next()) {
    			// key
    			// System.out.println("transform:" + rs2.getString(1) + "\t" + rs2.getString(2));
    		}
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            conn.close();
        }
}

 





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值