Java-JDBC连接

JDBC连接数据库[注意要引入驱动包mysql-connector-java]

import java.sql.*;

public class Connect {
    static Connection con; //声明Connect对象
    static Statement sql;   //声明Statement的对象
    static ResultSet res;   //声明ResultSet对象
    static String driver="com.mysql.jdbc.Driver";
    static String url="jdbc:mysql://localhost:3306/yh01_none_test";
    static String user="root";
    static String password="123456";
    public Connection getConn(){
        System.out.println("-----------------");
        try {
            Class.forName(driver);
            System.out.println("数据库驱动加载成功!");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            con = DriverManager.getConnection(url,user,password);
            System.out.println("数据库连接成功!");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }

    public static void main(String[] args) {
        Connect c=new Connect();
        con =c.getConn();
        try {
            sql= con.createStatement();
            res=sql.executeQuery("select * from student");
            while(res.next()){
                String id=res.getString("id");
                String number=res.getString("number");
                String name=res.getString("name");
                System.out.println("ID:"+id+"    number:"+number+"    name:"+name);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

 

posted @ 2019-10-21 20:34  Cool_Yang  阅读(146)  评论(0编辑  收藏  举报