java连接mysql

import java.sql.*;

public class MySQLDemo {
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    public void getConnect(){
        // MySQL 8.0 以下版本 - JDBC 驱动名及数据库 URL
        String JDBC_DRIVER = "com.mysql.jdbc.Driver";
        String DB_URL = "jdbc:mysql://localhost:3306/test_database";
        String USER = "root";
        String PASS = "root";
        try{
            Class.forName(JDBC_DRIVER);
            System.out.println("连接数据库");
            this.conn = DriverManager.getConnection(DB_URL,USER,PASS);
            System.out.println(" 实例化Statement对象...");
            this.stmt = this.conn.createStatement();


        }catch (Exception e){
            e.printStackTrace();
        }

    }
    public void closeConnect(){
        try{
            if(this.stmt!=null) this.stmt.close();
        }catch(SQLException se2){
        }// 什么都不做
        try{
            if(this.conn!=null) this.conn.close();
        }catch(SQLException se){
            se.printStackTrace();
        }
    }



    public static void main(String[] args) {

        MySQLDemo mySQLDemo = new MySQLDemo();
        mySQLDemo.getConnect();

        try{
            mySQLDemo.rs = mySQLDemo.stmt.executeQuery("select * from t_user");
            while(mySQLDemo.rs.next()){
                // 通过字段检索
                int id  = mySQLDemo.rs.getInt("id");
                String name = mySQLDemo.rs.getString("id");
                String url = mySQLDemo.rs.getString("password");

                // 输出数据
                System.out.print("ID: " + id);
                System.out.print(", 站点名称: " + name);
                System.out.print(", 站点 URL: " + url);
                System.out.print("\n");
            }
            mySQLDemo.rs.close();
            mySQLDemo.stmt.close();
            mySQLDemo.conn.close();
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            // 完成后关闭
            mySQLDemo.closeConnect();
        }



    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值