手动连接数据库(jdbc)

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


public class Test {

    public static void main(String[] args) throws Exception {
          String user="root";//数据库的用户名
           String pwd="";//数据库的密码
           String url="jdbc:mysql://localhost:3306/taotao";//taotao这个是你所要访问到数据库
           String driver="com.mysql.jdbc.Driver";
           Connection con=null;
           PreparedStatement stmt=null;
           ResultSet rs=null;
            try {
                Class.forName(driver);
                con=DriverManager.getConnection(url,user,pwd);
                stmt=con.prepareStatement("select * from tb_item");//这里面是对应的sql语句,对应数据库中相应的表格
                 rs=stmt.executeQuery();
                 while(rs.next()){
                     System.out.println(rs.getObject(1)+","+rs.getObject(2));
                 }
                
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            finally{
                if(rs!=null){
                    rs.close();
                }
                if(stmt!=null){
                    stmt.close();
                }
                if(con!=null){
                    con.close();
                }
            }
            
    }

}

原文地址:https://www.cnblogs.com/1314wamm/p/7280754.html