当前位置 : 主页 > 编程语言 > c++ >

JDBC连接数据代码

来源:互联网 收集:自由互联 发布时间:2021-07-03
gistfile1.txt package test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class DBConnection{ String driver="com.mysql.jdbc.Driver"; String url="jdbc:mysql://local
gistfile1.txt
package test;

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

    public class DBConnection{
        String driver="com.mysql.jdbc.Driver";
        String url="jdbc:mysql://localhost:3306/test"
        String username="root";
        String password="1234";

        public static Connection getConnection(){
                Connection conn = null;
                try{
                    Class.forName(driver);
                    conn=DriverManager.getConnection(url,username,password)
                }catch(SQLException e){
                    e.printStackTrace();
                }
            return conn;
        }

    	public static Statement getStatement(Connection conn) throws ClassNotFoundException {
						Statement stmt = null; 
						try {
								if(conn != null) {
									stmt = conn.createStatement();
								}
							} catch (SQLException e) {
								e.printStackTrace();
							}
											
						return stmt;
			}
				
			public static ResultSet getResultSet(Statement stmt, String sql) {
							ResultSet rs = null;
							try {
									if(stmt != null) {
									    rs = stmt.executeQuery(sql);
									}
								} catch (SQLException e) {
									e.printStackTrace();
								}
							return rs;
			}
					
			public static void closeConn(Connection conn) {
							try {
									if(conn != null) {
										conn.close();
										conn = null;
									}
								} catch (SQLException e) {
									e.printStackTrace();
								}
			}
					
			public static void closeStmt(Statement stmt) {
						try {
								if(stmt != null) {
									stmt.close();
								    stmt = null;
								}
							} catch (SQLException e) {
								e.printStackTrace();
							}
		        }
					
			public static void closeRs(ResultSet rs) {
							try {
									if(rs != null) {
										rs.close();
										rs = null;
									}
								} catch (SQLException e) {
									e.printStackTrace();
                                }
           	 }
    }
网友评论