基本的数据库增删改查

整理电脑无意间发现了这段代码,想起了自己刚入门的时候。发表出来,纪念下。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBConn
{
private String url = "jdbc:oracle:thin:@localhost:1521:orcl";

private String cls = "oracle.jdbc.driver.OracleDriver";

private String username = "system";

private String password = "manager";

//三属性、四方法
//三大核心接口
private Connection conn = null;

private PreparedStatement pstmt = null;

private ResultSet rs = null;

//四方法
/**
* 1 得到数据库连接
*/
public void getConnection()
{
try
{
Class.forName(cls);
conn = DriverManager.getConnection(url, username, password);
}
catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}

/**
* 封闭数据库连接
*/
public void closeConn()
{
if (null != rs)
{
try
{
rs.close();
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (null != pstmt)
{
try
{
pstmt.close();
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (null != conn)
{
try
{
conn.close();
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

/**
* 增 删 改语句
*/
public int execOther(final String strSQL, Object[] params)
{
this.getConnection();
System.out.println(strSQL);
try
{
pstmt = conn.prepareStatement(strSQL);
for (int i = 0; i < params.length; i++)
{
pstmt.setObject(i + 1, params[i]);
}
int affectRows = pstmt.executeUpdate();
return affectRows;
}
catch (SQLException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
return 0;
}

/**
* 查询语句
*/
public ResultSet execQuery(final String strSQL, Object[] params)
{
this.getConnection();
System.out.println(strSQL);
try
{
pstmt = conn.prepareStatement(strSQL);
for (int i = 0; i < params.length; i++)
{
pstmt.setObject(i + 1, params[i]);
}
rs = pstmt.executeQuery();
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return rs;
}
}

mian函数
public static void main(String[] args)
{
DBUtil dbUtil = new DBUtil();
String name = "tom";
String password = "tom";
Object[] params = new Object[] {password};
String strSQL = "select * from person where password=?";
ResultSet rs = dbUtil.execQuery(strSQL, params);
try
{
while (rs.next())
{
System.out.println(rs.getInt(1));
}
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值