📄 jdbcbean.java
字号:
package BookStore;
import java.io.*;
import java.sql.*;
import java.util.*;
import javax.naming.*;
import javax.sql.*;
public class JDBCBean implements Serializable{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
DataSource ds = null;
//构造方法,初始化环境,查找数据源
public JDBCBean()
{
try{
Context ctx = null;
// Put connection properties in to a hashtable
Hashtable ht = new Hashtable();
ht.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
ht.put(Context.PROVIDER_URL,
"t3://localhost:7001");
//获取 weblogic Server JNDI的初始上下文环境
ctx = new InitialContext(ht);
//查找 JNDI名字为 myConnection 的数据源
ds = (DataSource) ctx.lookup("myConnection");
}
catch (Exception e)
{
System.out.println("getConnection method is Error: " + e.getMessage());
}
}
//建立连接,此连接为JDBC-应用服务器连接,需要先建连接池与数据源
//且数据源的JNDI名字为myConnection
public void getJDBCConnection(){
try{
//从连接池里取出一个连接
conn = ds.getConnection();
//建立语句对象
stmt = conn.createStatement();
}
catch(Exception e){
System.out.println("Connection is Error: " + e.getMessage());
}
}
//关闭连接
public void closeConnect()
{
try
{
if (rs != null)
rs.close(); //关闭结果集
if (stmt != null)
stmt.close(); //关闭语句对象
if (conn != null)
conn.close(); //关闭连接
}
catch (Exception e)
{
System.out.println("myConnection is Error: " + e.getMessage());
rs = null;
stmt = null;
conn = null;
}
}
//查书的数量
public int queryNum(String bookBH)
{
String query = "SELECT * from BookInfo where BookBH ="+bookBH;
System.out.println(query);
try
{
if (conn == null)
//先连接数据库
getJDBCConnection();
System.out.println("connection ok");
rs = stmt.executeQuery(query);
System.out.println("query ok");
int temp = 0;
while(rs.next())
{
temp = rs.getInt("BookNumber");
}
System.out.println("数量为"+temp);
closeConnect();
return temp;
}
catch (Exception e)
{
System.out.println("executeQuery error here: " + e.getMessage());
}
closeConnect();
return 0;
}
//执行查询sql语句
public ResultSet selectBookInfo(){
rs = null;
String sql = "SELECT * FROM BookInfo";
try{
if(conn == null)
//先连接数据库
getJDBCConnection();
rs = stmt.executeQuery(sql); //执行查询sql语句
}catch(Exception e){
System.out.println("executeQuery error here: " + e.getMessage());
}
return rs;
}
//执行更新sql语句
public boolean executeUpdate(String bookBH,int newNum){
boolean update = false;
int rowCount = 0;
newNum--;
String sql = "UPDATE BookInfo SET BookNumber="+newNum+" WHERE BookBH="+bookBH;
System.out.println(sql);
try{
if(conn == null)
//如果没连接,先连接数据库
getJDBCConnection();
if(conn != null){ //有连接,则执行sql更新语句
stmt = conn.createStatement();
rowCount = stmt.executeUpdate(sql);
if(rowCount != 0)
update = true;
}
}catch(SQLException e){
System.err.println("Conn.executeUpdate " + e.getMessage());
}
//关闭连接
closeConnect();
return update;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -