首先我们在与数据库连接中应该注意几个问题:1 不允许重复取值 如:
ResultSet rs = stmt.executeQuery(sql);
if(rs.next())
{
System.out.printlin("name");
System.out.printlin("name");
}
像这种取值方式就是错误的
2:取值过程中不允许乱序取值 如:
ResultSet rs = stmt.executeQuery(sql);
if(rs.next())
{
System.out.printlin(1);
System.out.printlin(3);
System.out.printlin(2);
}
这种乱序取值也是错误不可取的
3:不允许交叉
其次,写出正确的JAVA中连接数据库的方法类
先建立一个com.viita.common的包,在包里面建立 BaseDao.java 数据库基本操作类
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement;
public class BaseDao { private Connection conn = null; private Statement stmt = null; private ResultSet rs = null; public BaseDao() { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); conn = DriverManager.getConnection("jdbc:odbc:test"); stmt = conn.createStatement(); } catch (Exception e) { // TODO Auto-generated catch block
e.printStackTrace(); } } public void executeUpdate(String sql) throws SQLException { stmt.executeUpdate(sql); System.out.println(sql); } public ResultSet executeQuery(String sql) throws SQLException { rs = stmt.executeQuery(sql); return rs; } public void close() { try { if(rs!=null) rs.close(); } catch (Exception e) { // TODO: handle exception
System.out.println(e); } try { if(stmt!=null) stmt.close(); } catch (Exception e) { // TODO: handle exception
System.out.println(e); } try { if(conn!=null) conn.close(); } catch (Exception e) { // TODO: handle exception
System.out.println(e); } } public static void main(String[] args) throws Exception { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection conn = DriverManager.getConnection("jdbc:odbc:Driver={MicroSoft Access Driver (*.mdb)};DBQ=C:\\accp.mdb","",""); Statement stmt = conn.createStatement(); String sql = "insert into userinfo (userName,passWord,sex,age,address) values ('zs','zs','female','2','accp')"; stmt.executeUpdate(sql); conn.close(); } }
|
接着我们建立com.viita.dao包,里面放 用来操作数据库增 删 改 查 等方法的类baseDao.java
import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List;
import com.accp.bean.UserinfoBean; import com.accp.common.BaseDao;
public class UserinfoDao {
//插入方法 public void saveUserinfo(UserinfoBean userinfo) throws SQLException { String sql = "insert into ..."; BaseDao db = new BaseDao(); try { db.executeUpdate(sql); } catch (SQLException e) { // TODO Auto-generated catch block
throw new SQLException("数据库操作错误:"+e); }finally { db.close(); } }
//获取数据库信息 public List getUserinfos() { List list = new ArrayList(); String sql = "select * from ..."; BaseDao db = new BaseDao(); ResultSet rs; try { rs = db.executeQuery(sql); while(rs.next()) { UserinfoBean bean = new UserinfoBean(); bean.setId(rs.getInt(1)); ....... list.add(bean); } } catch (SQLException e) { // TODO Auto-generated catch block
e.printStackTrace(); }finally { db.close(); } return list; } }
|
这样 就基本上完成了J2EE中对数据库的标准操作 切记:执行完方法必须关闭数据库的链接!
阅读(702) | 评论(0) | 转发(0) |