Java连接Mysql数据库

现在很多公司面试,直接给张A4纸手写代码,比如让写个jdbc连接数据库,代码很简单,就是有点长^_^,做个小笔记记录一下

1 首先是一个DBHelper类,代码为:

package com.thorin;

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

/**
 * Created by Thorin on 2014/10/10.
 */
public class DBHelper {
    //1.声明驱动变量driver
    public static final String driver = "com.mysql.jdbc.Driver";
    //2.声明Mysql连接地址url,这句如果不加?后面的参数,会出现Warning
    public static final String url = "jdbc:mysql://127.0.0.1:3306/Test?useUnicode=true&characterEncoding=utf-8&useSSL=false";
    //3.声明数据库用户
    public static final String username = "root";
    //4.声明连接数据库的密码
    public static final String password = "12345";
    //5.初始化数据库连接实例conn
    public Connection conn = null;
    public PreparedStatement pst = null;
    //构造函数
    public DBHelper(String sql){
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url,username,password);
            pst = conn.prepareStatement(sql);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void close(){
        try {
            this.conn.close();
            this.pst.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

2 主函数代码为:

package com.thorin;

import java.sql.Connection;
import java.sql.ResultSet;

public class Main {

    static String sql = null;
    static DBHelper dbl = null;
    static ResultSet ret = null;

    public static void main(String[] args) {
        sql = "select * from user";
        dbl = new DBHelper(sql);

        try {
            ret = dbl.pst.executeQuery();
            while (ret.next()){
                String uid = ret.getString(1);
                String uname = ret.getString(2);
                String uage = ret.getString(3);
                System.out.println("id is " + uid + ", uname is " + uname + ", uage is " + uage);
            }
            ret.close();
            dbl.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3 效果图为:
result

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值