文本浏览器

JDBC配合MySQL工作实例

发布者 : 管理员-Adler | 发布时间 : 2019-01-17 19:19:48
文章号 : 35 | 阅读量 : 122+1 | AAW值(?) : 0.00 (仅供参考)

JDBCUtils.java

import java.sql.Connection;
import 
java.sql.DriverManager;
import 
java.sql.ResultSet;
import 
java.sql.SQLException;
import 
java.sql.Statement;
public final class 
JDBCUtils {
    
private static String url "jdbc:mysql://localhost:3306/jdbc";
    private static 
String user "root";
    private static 
String password "six";
    private 
JDBCUtils(){
    }
    
static{
        
// 1.注册驱动
        
try {
            Class.forName(
"com.mysql.jdbc.Driver");
        
catch (ClassNotFoundException e) {
            
throw new ExceptionInInitializerError(e);
        
}
    }
    
public static Connection getConnection() throws SQLException{
        
return DriverManager.getConnection(urluserpassword);
    
}
    
public static void free(ResultSet rs,Statement st,Connection conn){
        
try{
            
if(rs!=null){
                rs.close()
;
            
}
        }
catch(SQLException e){
            e.printStackTrace()
;
        
}finally{
            
try{
                
if(st != null){
                    st.close()
;
                
}
            }
catch(SQLException e){
                e.printStackTrace()
;
            
}finally{
                
if(conn!=null){
                    
try {
                        conn.close()
;
                    
catch (SQLException e) {
                       e.printStackTrace()
;
                    
}
                }
            }
        }
    }
}

main.java

import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.Statement;



public class main {



    public static void main(String[] args) throws Exception {

        // TODO Auto-generated method stub

        template();

    }



    static void template() throws Exception{



        Connection conn = null;

        Statement st = null;

        ResultSet rs = null;



        try {



            // 2.建立连接             conn = JDBCUtils.getConnection();



            // 3.创建语句             st = conn.createStatement();



            // 4.执行语句             rs = st.executeQuery("select * from user");



            // 5.处理结果             while(rs.next()){

                System.out.println(rs.getObject(1) + "\t" + rs.getObject(2)

                        + "\t"+ rs.getObject(3)+"\t" + rs.getObject(4));

            }

            rs = st.executeQuery("select * from user2"); //再次查询             while(rs.next()){

                System.out.println(rs.getObject(1) + "\t" + rs.getObject(2)

                        + "\t"+ rs.getObject(3)+"\t" + rs.getObject(4));

            }

        }finally{

            JDBCUtils.free(rs, st, conn);

        }

    }

}





评论加载中...

+ 参与讨论