?? dbutil.java
字號(hào):
package javastudy.tools;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.*;
import java.util.ArrayList;
import java.util.Vector;
public class DBUtil
{
public static ArrayList execute(String sqlString)
{
String name;
int math, chinese, english;
Connection con = null;//聲明一個(gè)連接的引用對(duì)象
Statement stat = null;//聲明一個(gè)連接狀態(tài)的引用對(duì)象
ResultSet rs = null;//聲明一個(gè)結(jié)果集對(duì)象
try//在搭建窗口時(shí)創(chuàng)建數(shù)據(jù)連接驅(qū)動(dòng),避免創(chuàng)建連接過(guò)程中重復(fù)定義
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException e1)
{
System.out.println("數(shù)據(jù)庫(kù)驅(qū)動(dòng)錯(cuò)誤");
}
try
{
con = DriverManager.getConnection("jdbc:odbc:datasourcename", "", "");//數(shù)據(jù)源,用戶名,密碼
stat = con.createStatement();//得到連接狀態(tài)
if(sqlString.trim().substring(0, 1).equalsIgnoreCase("s"))
{
//String t=new java.util.Date().toLocaleString().toString();
//stat.executeUpdate("insert into tablename (name,math,chinese,english) values('李四',23,43,54)");
//stat.executeUpdate("update tablename set name='小李四',math=100,chinese=100,english=100 where id=4");
//stat.executeUpdate("delete from tablename where math<60");
rs = stat.executeQuery(sqlString);
ArrayList al=new ArrayList();
while(rs.next())
{
Vector v=new Vector(5);
v.add(rs.getString(1));
v.add(rs.getString(2));
v.add(rs.getString(3));
v.add(rs.getString(4));
v.add(rs.getString(5));
al.add(v);
}
if(!al.isEmpty())
{
return al;
}
//return rs;
/*
while(rs.next())
{
name = rs.getString("name");
math = rs.getInt("math");
chinese = rs.getInt("chinese");
english = rs.getInt("english");
System.out.println("***********************************************");
System.out.println("id:" + rs.getString("id") + "\t姓名: " + name + "\t" + "數(shù)學(xué)= " + math + "\t" + "語(yǔ)文= " + chinese + "\t");
//System.out.println(substance);
System.out.println("***********************************************");
System.out.println("");
}*/
}
else
{
stat.executeUpdate(sqlString);
}
if(rs != null)
rs.close();
if(stat != null)
stat.close();
if(con != null)
con.close();
}
catch(SQLException e2)
{
//System.out.println("數(shù)據(jù)庫(kù)連接失敗");
e2.printStackTrace();
}
return null;
}
public static void main(String[] args)
{
// TODO: Add your code here
DBUtil.execute("select * from tablename");
}
}
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -