當前位置:首頁 » 數據倉庫 » javaDAO連接資料庫
擴展閱讀
webinf下怎麼引入js 2023-08-31 21:54:13
堡壘機怎麼打開web 2023-08-31 21:54:11

javaDAO連接資料庫

發布時間: 2022-04-30 21:11:33

⑴ java連接資料庫DAO

再寫一個類,聲明一個List類的方法,先調用DAO方法,然後用迭代器(Iterator)迭代結果

⑵ Java連接資料庫為什麼要用Dao

我的理解只是為了封裝,方便業務層組裝調用來完成業務,這樣代碼的結構會比較好

⑶ java用Dao訪問資料庫,如何執行sql語句

你說的DAO是 做的一層專門負責資料庫操作的邏輯層,具體你是hibernate,ibatis,jdbc你沒說,所以不便於回答。
用的hibernate的話 getSession.update(String sql,Object params);

⑷ java如何通過Dao介面取得資料庫數據【謝謝】

import java.util.List;

import com.icss.xxx.domain.User;

public interface UserDAO {
public int login(User user);

public User queryUser(String userId) throws Exception;

public int updateUser(User user);

public int addUser(User user);

public int deleteUser(String userId) throws Exception;

public List getAllUsers();

public User getUser(String userName) throws Exception;

}

---------------------------------------
下面是實現類

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.xxx.xxx.common.ConnectionFactory;
import com.xxx.xxx.common.DatabaseUtils;
import com.xxx.xxx..UserDAO;
import com.xxx.xxx.domain.User;

public class UserDAOImpl implements UserDAO {

public List getAllUsers() {
Connection conn=ConnectionFactory.getConnection();
List users=new ArrayList();
Statement stmt=null;
ResultSet rs=null;
try {
stmt=conn.createStatement();
rs=stmt.executeQuery("select * from training");
User user=null;
while(rs.next()){
user=new User();
user.setUserId(rs.getString("userid"));
user.setUserName(rs.getString("username"));
user.setUserPass(rs.getString("userpass"));
users.add(user);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
DatabaseUtils.release(rs, stmt, conn);
}
return users;
}

public int login(User user) {
int flag=0;
Connection conn=ConnectionFactory.getConnection();
PreparedStatement pstm=null;
ResultSet rs=null;
try {
pstm=conn.prepareStatement("select * from train_user where user_name=? and user_pass=?");
pstm.setString(1, user.getUserName());
pstm.setString(2, user.getUserPass());
rs=pstm.executeQuery();
if(rs.next()){
if(rs.getString("admin").equals("1")){
flag=1;
}else if(rs.getString("admin").equals("0")){
flag=2;
}else{
flag=0;
};
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
DatabaseUtils.release(rs, pstm, conn);
}
return flag;
}

public User queryUser(String userId) {

Connection conn = ConnectionFactory.getConnection();
PreparedStatement pstm = null;
ResultSet rs = null;
User user = null;

try {

pstm = conn.prepareStatement("select * from test where userid=?");
pstm.setString(1, userId);
rs = pstm.executeQuery();

if(rs.next()){
user = new User();
user.setUserId(rs.getString("userid"));
user.setUserName(rs.getString("username"));
user.setUserPass(rs.getString("userPass"));

}

} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{

DatabaseUtils.release(rs, pstm, conn);
}

return user;
}

public int updateUser(User user) {

Connection conn = ConnectionFactory.getConnection();
PreparedStatement pstm = null;
ResultSet rs = null;

int flag = 0;
try {

pstm = conn.prepareStatement("update test set username=?, userpass=? where userid=?");

pstm.setString(1, user.getUserName());

pstm.setString(2, user.getUserPass());

pstm.setString(3, user.getUserId());

flag = pstm.executeUpdate();

} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{

DatabaseUtils.release(rs, pstm, conn);
}

return flag;
}

public int addUser(User user) {
Connection conn=ConnectionFactory.getConnection();
PreparedStatement pstm=null;
int flag=0;
try {
pstm=conn.prepareStatement("insert into train_user(user_id,user_name,user_pass,train_id,train_nature,admin) values(?,?,?,?,?,0)");
pstm.setString(1,user.getUserId());
pstm.setString(2,user.getUserName());
pstm.setString(3,user.getUserPass());
pstm.setString(4,user.getTrain_id());
pstm.setString(5,user.getTrain_nature());
pstm.executeUpdate();
flag=1;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{

DatabaseUtils.release(null, pstm, conn);
}
return flag;
}

public int deleteUser(String userId) throws Exception {

Connection conn = ConnectionFactory.getConnection();
PreparedStatement pstm = null;
int flag = 0;
try {

pstm = conn.prepareStatement("delete from test where userid=?");

pstm.setString(1, userId);

flag = pstm.executeUpdate();

} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{

DatabaseUtils.release(null, pstm, conn);
}
return flag;

}

public User getUser(String userName) throws Exception {
// TODO Auto-generated method stub
return null;
}

}

⑸ java中如何實現登錄界面與資料庫正確連接

使用JDBC進行資料庫的增刪改查操作1.下載Microsoft SQL Server 2005 JDBC 驅動包jar文件 將jar文件引入工程中2.封裝資料庫鏈接的獲取和關閉操作import java.sql.*;public class BaseDao {
/**
* 資料庫驅動類的字元串,完整的包名加類名 在工程中查看添加的jar文件 能看到這個類
*/
private static final String DRIVE = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; /**
* 資料庫連接地址
*
* DataBaseName=資料庫名稱 其它固定
*/
private static final String URL = "jdbc:sqlserver://localhost:1433;DataBaseName=bbs"; /**
* 連接資料庫的用戶名
*/
private static final String USER = "sa"; /**
* 用戶密碼
*/
private static final String PASSWORD = ""; /**
* 獲取連接 異常直接拋出 或者捕獲後自定義異常信息再拋出
*/
public static Connection getConnection() throws Exception {
Class.forName(DRIVE);
return DriverManager.getConnection(URL, USER, PASSWORD);
} /**
* 關閉與資料庫的連接 釋放資源
*/
public static void closeAll(ResultSet resultSet, PreparedStatement pst,
Connection connection) throws Exception {
if (resultSet != null)
resultSet.close();
if (pst != null)
pst.close();
if (connection != null)
connection.close();
}}3.創建圖書的實體類public class Book {
/**
* 資料庫主鍵
*/
private Long id; /**
* 作者
*/
private String author; /**
* 書名
*/
private String name;
/**
* 默認構造
*
*/
public Book() {
}
/**
* 全欄位構造
* @param id
* @param author
* @param name
*/
public Book(Long id, String author, String name) {
this.id = id;
this.author = author;
this.name = name;
}
/**
* 以下為讀寫屬性的方法
* @return
*/
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
4.創建與圖書表交互的工具類import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;public class BookDao {
/**
* 添加新書
*
* @param book 要添加入資料庫的圖書 作者 書名 必須給定
*/
public void addBook(Book book) throws Exception {
// 連接
Connection connection = null;
// 執行語句
PreparedStatement pst = null;
try {
connection = BaseDao.getConnection();
// 構造執行語句
String sql = "insert into book values(" + book.getAuthor() + ","
+ book.getName() + ")";
pst = connection.prepareStatement(sql);
pst.executeUpdate(); } catch (Exception e) {
// 拋出異常
throw e;
} finally {
// 無論是否異常 均關閉資料庫
BaseDao.closeAll(null, pst, connection);
}
} /**
* 查詢所有書籍列表
*/
public List<Book> getBooks() throws Exception {
// 用於存放查尋結果的集合
List<Book> books = new ArrayList<Book>();
// 連接
Connection connection = null;
// 執行語句
PreparedStatement pst = null;
// 查詢結果
ResultSet resultSet = null;
try {
connection = BaseDao.getConnection();
// 構造查詢語句
String sql = "select * from book";
pst = connection.prepareStatement(sql);
resultSet = pst.executeQuery(); // 循環讀取查詢結果行
while (resultSet.next()) {
// getXXX的參數為數據表列名
Book book = new Book(resultSet.getLong("id"), resultSet
.getString("author"), resultSet.getString("name"));
// 將封裝好的圖書對象存入集合
books.add(book);
}
} catch (Exception e) {
// 拋出異常
throw e;
} finally {
// 無論是否異常 均關閉資料庫
BaseDao.closeAll(resultSet, pst, connection);
}
// 返回查詢結果
return books;
}/***其它方法類似上面 只是語句不同*/
}當然 以上只是簡單的封裝 初學者可以在理解以上代碼的基礎上 進行更高級的封裝
5.使用BookDao添加書籍和獲取所有書籍列表import java.util.List;/**
* 測試類
* @author Administrator
*
*/
public class Test { /**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
//創建工具類對象
BookDao = new BookDao();
//創建一本圖書
Book book = new Book(null,"QQ:495691293","編程菜鳥");
//添加書籍到資料庫
.addBook(book);

//獲取所有圖書列表
List<Book> books = .getBooks();
//輸出結果
for (Book b : books) {
System.out.println(b.getId()+"\t"+b.getAuthor()+"\t"+b.getName());
}
}}

⑹ java關於操作資料庫

用Hibernate。Hibernate可以根據實體類和配置文件自動生成sql語句,這樣只用寫一個通用的DAO然後其他DAO繼承它後就自然有對應的增刪改查功能了。比如我的DAO一般就
@Repository("brandDAO")
public class BrandDAO extends HibernateDao<Integer> {
}

⑺ 剛學java 操作資料庫,不太懂

Dao層是Java web的三層架構的持久化層。Dao 的工廠類是用來創建的對象。採用的時工廠模式。我比較常用的時用單例模式來創建的對象。至於Dao借口,如果你只是一個測試的東東,力求簡化,這個當然可以去去掉的。但是你如果是做開發項目,你就會發現這個的用處。

還有,現在開發web項目都會使用框架了,比如spring框架,就可以建立相當明晰的三層框架。

這是我用spring建立的一個web的簡單項目的框架結構。domain是ORM映射類,資料庫操作類,持久層,service是服務層,提供事務管理可工作流程的控制,web層攔截請求,返回結果。

⑻ java中,用DAO查詢一個資料庫步驟,分哪幾個步驟,原理解析

創建一個以JDBC連接資料庫的程序,包含7個步驟:
1、載入JDBC驅動程序:
在連接資料庫之前,首先要載入想要連接的資料庫的驅動到JVM(Java虛擬機),
這通過java.lang.Class類的靜態方法forName(String className)實現。
例如:
try{
//載入MySql的驅動類
Class.forName("com.mysql.jdbc.Driver") ;
}catch(ClassNotFoundException e){
System.out.println("找不到驅動程序類 ,載入驅動失敗!");
e.printStackTrace() ;
}
成功載入後,會將Driver類的實例注冊到DriverManager類中。
2、提供JDBC連接的URL
•連接URL定義了連接資料庫時的協議、子協議、數據源標識。
•書寫形式:協議:子協議:數據源標識
協議:在JDBC中總是以jdbc開始
子協議:是橋連接的驅動程序或是資料庫管理系統名稱。
數據源標識:標記找到資料庫來源的地址與連接埠。
例如:(MySql的連接URL)
jdbc:mysql:
//localhost:3306/test?useUnicode=true&characterEncoding=gbk ;
useUnicode=true:表示使用Unicode字元集。如果characterEncoding設置為
gb2312或GBK,本參數必須設置為true 。characterEncoding=gbk:字元編碼方式。
3、創建資料庫的連接
•要連接資料庫,需要向java.sql.DriverManager請求並獲得Connection對象,
該對象就代表一個資料庫的連接。
•使用DriverManager的getConnectin(String url , String username ,
String password )方法傳入指定的欲連接的資料庫的路徑、資料庫的用戶名和
密碼來獲得。
例如:
//連接MySql資料庫,用戶名和密碼都是root
String url = "jdbc:mysql://localhost:3306/test" ;
String username = "root" ;
String password = "root" ;
try{
Connection con =
DriverManager.getConnection(url , username , password ) ;
}catch(SQLException se){
System.out.println("資料庫連接失敗!");
se.printStackTrace() ;
}
4、創建一個Statement
•要執行SQL語句,必須獲得java.sql.Statement實例,Statement實例分為以下3
種類型:
1、執行靜態SQL語句。通常通過Statement實例實現。
2、執行動態SQL語句。通常通過PreparedStatement實例實現。
3、執行資料庫存儲過程。通常通過CallableStatement實例實現。
具體的實現方式:
Statement stmt = con.createStatement() ;
PreparedStatement pstmt = con.prepareStatement(sql) ;
CallableStatement cstmt =
con.prepareCall("{CALL demoSp(? , ?)}") ;
5、執行SQL語句
Statement介面提供了三種執行SQL語句的方法:executeQuery 、executeUpdate
和execute
1、ResultSet executeQuery(String sqlString):執行查詢資料庫的SQL語句
,返回一個結果集(ResultSet)對象。
2、int executeUpdate(String sqlString):用於執行INSERT、UPDATE或
DELETE語句以及SQL DDL語句,如:CREATE TABLE和DROP TABLE等
3、execute(sqlString):用於執行返回多個結果集、多個更新計數或二者組合的
語句。
具體實現的代碼:
ResultSet rs = stmt.executeQuery("SELECT * FROM ...") ;
int rows = stmt.executeUpdate("INSERT INTO ...") ;
boolean flag = stmt.execute(String sql) ;
6、處理結果
兩種情況:
1、執行更新返回的是本次操作影響到的記錄數。
2、執行查詢返回的結果是一個ResultSet對象。
• ResultSet包含符合SQL語句中條件的所有行,並且它通過一套get方法提供了對這些
行中數據的訪問。
• 使用結果集(ResultSet)對象的訪問方法獲取數據:
while(rs.next()){
String name = rs.getString("name") ;
String pass = rs.getString(1) ; // 此方法比較高效
}
(列是從左到右編號的,並且從列1開始)
7、關閉JDBC對象
操作完成以後要把所有使用的JDBC對象全都關閉,以釋放JDBC資源,關閉順序和聲
明順序相反:
1、關閉記錄集
2、關閉聲明
3、關閉連接對象
if(rs != null){ // 關閉記錄集
try{
rs.close() ;
}catch(SQLException e){
e.printStackTrace() ;
}
}
if(stmt != null){ // 關閉聲明
try{
stmt.close() ;
}catch(SQLException e){
e.printStackTrace() ;
}
}
if(conn != null){ // 關閉連接對象
try{
conn.close() ;
}catch(SQLException e){
e.printStackTrace() ;
}
}

⑼ java怎麼連接mysql資料庫

這里介紹兩種方式:

一,jdbc鏈接MySQL資料庫:

1,如果你用jdbc方式,則按照下列方式進行連接:

A,注冊驅動

B,鏈接資料庫

C,執行sql

D,返回結果集

如下為一個基本完整流程:

packagecom.hu.demo;

importjava.sql.Connection;
importjava.sql.DriverManager;
importjava.sql.PreparedStatement;
importjava.sql.SQLException;

publicclassDBHelper{
publicstaticfinalStringurl="jdbc:mysql://127.0.0.1/student";
publicstaticfinalStringname="com.mysql.jdbc.Driver";
publicstaticfinalStringuser="root";
="root";

publicConnectionconn=null;
publicPreparedStatementpst=null;

publicDBHelper(Stringsql){
try{
Class.forName(name);//指定連接類型
conn=DriverManager.getConnection(url,user,password);//獲取連接
pst=conn.prepareStatement(sql);//准備執行語句
}catch(Exceptione){
e.printStackTrace();
}
}

publicvoidclose(){
try{
this.conn.close();
this.pst.close();
}catch(SQLExceptione){
e.printStackTrace();
}
}
}

2,將注冊,鏈接封裝好,執行sql語句,返回結果集,代碼如下:

packagecom.hu.demo;

importjava.sql.ResultSet;
importjava.sql.SQLException;

publicclassDemo{

staticStringsql=null;
staticDBHelperdb1=null;
staticResultSetret=null;

publicstaticvoidmain(String[]args){
sql="select*fromstuinfo";//SQL語句
db1=newDBHelper(sql);//創建DBHelper對象

try{
ret=db1.pst.executeQuery();//執行語句,得到結果集
while(ret.next()){
Stringuid=ret.getString(1);
Stringufname=ret.getString(2);
Stringulname=ret.getString(3);
Stringudate=ret.getString(4);
System.out.println(uid+" "+ufname+" "+ulname+" "+udate);
}//顯示數據
ret.close();
db1.close();//關閉連接
}catch(SQLExceptione){
e.printStackTrace();
}
}

}

3,查詢結果如下:

<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">

<!--配置數據源-->
<beanname="dataSource"class="com.alibaba.druid.pool.DruidDataSource"
init-method="init"destroy-method="close">
<propertyname="url"value="${jdbc_url}"/>
<propertyname="username"value="${jdbc_username}"/>
<propertyname="password"value="${jdbc_password}"/>

<!--初始化連接大小-->
<propertyname="initialSize"value="0"/>
<!--連接池最大使用連接數量-->
<propertyname="maxActive"value="20"/>
<!--連接池最小空閑-->
<propertyname="minIdle"value="0"/>
<!--獲取連接最大等待時間-->
<propertyname="maxWait"value="60000"/>

<!--<propertyname="poolPreparedStatements"value="true"/><property
name=""value="33"/>-->

<propertyname="validationQuery"value="${validationQuery}"/>
<propertyname="testOnBorrow"value="false"/>
<propertyname="testOnReturn"value="false"/>
<propertyname="testWhileIdle"value="true"/>

<!--配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒-->
<propertyname="timeBetweenEvictionRunsMillis"value="60000"/>
<!--配置一個連接在池中最小生存的時間,單位是毫秒-->
<propertyname="minEvictableIdleTimeMillis"value="25200000"/>

<!--打開removeAbandoned功能-->
<propertyname="removeAbandoned"value="true"/>
<!--1800秒,也就是30分鍾-->
<propertyname="removeAbandonedTimeout"value="1800"/>
<!--關閉abanded連接時輸出錯誤日誌-->
<propertyname="logAbandoned"value="true"/>

<!--監控資料庫-->
<!--<propertyname="filters"value="stat"/>-->
<propertyname="filters"value="mergeStat"/>
</bean>

<!--myBatis文件-->
<beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">
<propertyname="dataSource"ref="dataSource"/>
<!--自動掃描entity目錄,省掉Configuration.xml里的手工配置-->
<propertyname="mapperLocations"value="classpath:com/fourfaith/*/mapping/*.xml"/>
</bean>

<beanclass="org.mybatis.spring.mapper.MapperScannerConfigurer">
<propertyname="basePackage"value="com.fourfaith.**."/>
<propertyname="sqlSessionFactoryBeanName"value="sqlSessionFactory"/>
</bean>

<!--配置事務管理器-->
<beanid="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<propertyname="dataSource"ref="dataSource"/>
</bean>

<!--攔截器方式配置事物-->
<tx:adviceid="transactionAdvice"transaction-manager="transactionManager">
<tx:attributes>
<tx:methodname="add*"propagation="REQUIRED"/>
<tx:methodname="append*"propagation="REQUIRED"/>
<tx:methodname="insert*"propagation="REQUIRED"/>
<tx:methodname="save*"propagation="REQUIRED"/>
<tx:methodname="update*"propagation="REQUIRED"/>
<tx:methodname="modify*"propagation="REQUIRED"/>
<tx:methodname="edit*"propagation="REQUIRED"/>
<tx:methodname="delete*"propagation="REQUIRED"/>
<tx:methodname="remove*"propagation="REQUIRED"/>
<tx:methodname="repair"propagation="REQUIRED"/>
<tx:methodname="delAndRepair"propagation="REQUIRED"/>
<tx:methodname="import*"propagation="REQUIRED"read-only="false"
rollback-for="java.lang.Exception"/>

<tx:methodname="get*"propagation="SUPPORTS"/>
<tx:methodname="find*"propagation="SUPPORTS"/>
<tx:methodname="load*"propagation="SUPPORTS"/>
<tx:methodname="search*"propagation="SUPPORTS"/>
<tx:methodname="datagrid*"propagation="SUPPORTS"/>

<tx:methodname="*"propagation="SUPPORTS"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcutid="transactionPointcut"
expression="execution(*com...*.service..*Impl.*(..))"/>
<aop:advisorpointcut-ref="transactionPointcut"
advice-ref="transactionAdvice"/>
</aop:config>

<!--配置druid監控springjdbc-->
<beanid="druid-stat-interceptor"
class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">
</bean>
<beanid="druid-stat-pointcut"class="org.springframework.aop.support.JdkRegexpMethodPointcut"
scope="prototype">
<propertyname="patterns">
<list>
<value>com...*.service.*</value>
</list>
</property>
</bean>

<aop:config>
<aop:advisoradvice-ref="druid-stat-interceptor"
pointcut-ref="druid-stat-pointcut"/>
</aop:config>
</beans>

還有很多方式可以實現,這里就簡略的描述一番。

⑽ java中Dao如何訪問資料庫

用java訪問資料庫需要4步驟,只要按這個做就可以輕松訪問資料庫。

1、載入資料庫驅動
2、獲得資料庫連接
3、執行sql語句
4、(處理結果集)
5、關閉資源
第4歩看你的sql語句了,如果有返回結果則有第4歩,否則不用。

具體的:用一個類做例子
public class UserDaoImpl{
public void insertUserMessage(String name,String pwd){
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
//上面是載入資料庫驅動
String url="jdbc:oracle:thin:@localhost:1521:orcl";
//orcl為資料庫的SID
String user="test";//這個是資料庫的登錄用戶名
String password="test"; //登錄密碼
Connection conn =DriverManager.getConnection (url,user,password);
//獲得資料庫連接
PreparedStatement pst = conn.prepareStatement("Sql語句");
pst.setString(1,name);
pst.setString(2,pwd);
pst.excute();

pst.close();//關閉資源
conn.close();
}
}
以上就是連接資料庫的偽碼,不知道對你有沒有幫助