现在很多公司面试,直接给张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 效果图为: