JDBC连接数据库并更新

package test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class TestConnection {
	
	static Connection con = null;
	
	public static void main(String[] args) {
		PreparedStatement pstmt = null;
		try {
			con = getConnection();
			pstmt = con.prepareStatement("update user set username = ? where id = ? ");
			pstmt.setString(1, "newName");
			pstmt.setInt(2, 2);
			pstmt.executeUpdate();
		}catch (SQLException e) {
			System.out.println("");
		}finally {
			closeDB(pstmt);
			closeDB(con);
		}
	}

	public static Connection getConnection(){  
        try{  
            Class.forName("com.mysql.jdbc.Driver");  
            con=DriverManager.getConnection("url","username","password");  
            System.out.println("连接数据库成功");  
        }catch(Exception e){  
            System.out.println("建立数据库连接发生错误!" + e.getStackTrace());  
        }finally{  
            return con;  
        }  
    } 
	
	public static void closeDB(PreparedStatement pstmt) {
		if (pstmt != null) {
			try {
				pstmt.close();
			} catch (Exception ex) {
				System.out.println("" + ex.getStackTrace());
			}
		}
	}

	public static void closeDB(Connection con) {
		if (con != null) {
			try {
				con.close();
			} catch (Exception ex) {
				System.out.println("" + ex.getStackTrace());
			}
		}
	}
    
    
}

 

你可能感兴趣的:(jdbc)