java连接mysql数据库

Java利用JDBC访问数据库的编程步骤
1)加载连接数据库的驱动程序 Class.forName("com.mysql.jdbc.Driver");   
2)创建与数据源的连接
tring url ="jdbc:mysql://localhost:3306/databases"
Connection conn=DriverManager.getConnection(url,"user","Password");
3)查询数据库:创建Statement对象并执行SQL语句以返回一个ResultSet对象。
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery("select * from DBTableName");
4)获得当前记录集中的某一记录的各个字段的值
String name=rs.getString("Name");
int age=rs.getInt("age");
float wage=rs.getFloat("wage");
5)关闭查询语句及与数据库的连接(注意关闭的顺序先rs再stmt最后为conn)
rs.close();   
stmt.close();
con.close();

import java.sql.*;
public class WebRs {
    private Connection conn=null;
    private Statement stmt=null;
    private ResultSet rs=null;
    private ResultSetMetaData stmd=null;
    public WebRs(String dri,String user,String pass,String url){
        try {
            Class.forName(dri);
        } catch (Exception e) {
            System.out.println("加载驱动异常");
        }
        try {
            conn=DriverManager.getConnection(url,user,pass);
            if(conn!=null){
                stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
            }
        } catch (Exception e) {
            System.out.println("数据库链接失败");
        }
    }
    public ResultSet getres(String sql){
        try {
            rs=stmt.executeQuery(sql);
            if(rs!=null){
            return rs;   
            }else{
                return null;
            }
        } catch (Exception e) {
            System.out.println("数据库查询失败");
        }
        return rs;
    }
    public static void main(String[] args) throws SQLException{
        String driver="com.mysql.jdbc.Driver";
        String url="jdbc:mysql://localhost:3306/mysql";
        String sql="select * from user";
        WebRs mysql=new WebRs(driver,"root","pass",url);
        ResultSet rs=mysql.getres(sql);
        while(rs.next()){
            System.out.println(rs.getString(1));
        }
    }
   
}

你可能感兴趣的:(java,sql,编程,mysql,jdbc)