📄 databasebean.java
字号:
package jdbcbook.pub.db;
import java.sql.*;
/*
* 数据库相关操作
*/
public class DatabaseBean
{
public static Connection getConnection(String user,String password) throws SQLException
{
//定义驱动程序
String DRIVER="oracle.jdbd.driver.OracleDriver";
//定义连接字符串
String CONNSTR="jdbc:oracle:oci11g:"+user+"/"+password+"@test";
try
{
Class.forName(DRIVER);
}
catch(ClassNotFoundException e)
{
e.printStackTrace(System.err);
}
return DriverManager.getConnection(CONNSTR);
}
//取得某个表中可用的主键值
public static synchronized int getMaxID(Connection conn,String tablename) throws SQLException
{
int nMaxID=0;
Statement st=conn.createStatement();
//增加同步,避免同时多个线程执行
String sql="select maxid from tableseq where tablename='"+tablename+"'";
ResultSet rs=st.executeQuery(sql);
while(rs.next())
{
nMaxID=rs.getInt(1);
}
rs.close();
if(nMaxID>0)
{
//存在该表的记录
nMaxID++;
sql="update tableseq set maxid='"+nMaxID+"' where tablename='"+tablename+"'";
}
else
{
//不存在该表记录
nMaxID=1;
sql="insert into tableseq(tablename,maxid) values('"+tablename+"','"+nMaxID+"')";
}
st.executeUpdate(sql);
st.close();
return nMaxID;
}
//关闭连接,释放资源
public static void close(ResultSet rs,Statement st,Connection conn)
{
try
{
if(rs==null)
rs.close();
}
catch(SQLException e)
{}
try
{
if(st==null)
st.close();
}
catch(SQLException e)
{}
try
{
if(conn==null)
conn.close();
}
catch(SQLException e)
{}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -