JDBC浅析
今天简单的说一下jdbc,本来这玩意儿也很简单。
大家只需要记住其中的几个重要的类就行了,它们都在sql包里。今天主要是拿mysql来连接。先看一下主要的几个类吧。
1.Conenction
2.Statement
3.ResultSet
废话不多说我直接上代码了,因为实在很简单
import java.sql.*;
//Java DataBase Connectivity
public class Main {
public static void main(String[] args) {
}
}
class Init{
//用于连接的账号和密码
private String user;
private String passw;
private String protocol;
//收集statement connenction resultset的对象方便清理
private Statement statement = null;
private Connection connection = null;
private ResultSet resultset = null;
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassw() {
return passw;
}
public void setPassw(String passw) {
this.passw = passw;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
//返回一个connection引用的方法
public Connection getConnection() throws ClassNotFoundException{
//利用反射动态加载Driver
Class.forName("com.mysql.jdbc.Driver");
//返回一个Connection对象
Connection connection = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/student",user,passw);
} catch (SQLException e) {
//捕获打印异常栈
e.printStackTrace();
}
return connection;
}
//返回一个Statement的对象
public Statement getStatement(){
Statement statement = null;
try {
statement = getConnection().createStatement();
} catch (ClassNotFoundException | SQLException e) {
//捕获打印异常栈
e.printStackTrace();
}
return statement;
}
//对表进行增加数据的操作
public void IDU(String s){
//statement 被调用返回给字段statement
if(statement == null){
statement = getStatement();
}
try {
statement.executeUpdate(s);
} catch (SQLException e) {
e.printStackTrace();
}
finally{
clear();
}
}
//表的查询
public void queryData(String s){
if(statement == null){
statement = getStatement();
}
try {
resultset = statement.executeQuery(s);
ResultSetMetaData rsmd = resultset.getMetaData();
//获取字段长度
int count = rsmd.getColumnCount();
//遍历数据
while(resultset.next()){
for(int i = 1;i<= count;i++){
System.out.println(resultset.getObject(i));
}
}
} catch (SQLException e) {
//打印异常栈
e.printStackTrace();
}
finally{
clear();
}
}
//对各个占用资源的类进行清理
public void clear(){
try{
if(statement != null){
statement.close();
}
if(connection != null){
connection.close();
}
if(resultset != null){
resultset.close();
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
相信大家都能看懂,哪里不懂或者是哪里有错误请在回复区指出。😃