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

java實現資料庫操作

發布時間: 2022-05-06 04:17:19

Ⅰ 在java中怎麼對資料庫的數據進行操作

首先,你要先有一個資料庫。
然後下在你的資料庫對應的JDBC驅動。
將驅動的jar包放到項目的classpath。
然後就可以編寫程序來連接資料庫,並進行保存和查詢操作了。
保存數據通過執行INSERT INTO語句
查詢數據通過SELECT語句

總之,如果是新手,需要了解的只是挺多的。先看看JDBC的內容吧。

如果不想了解太多細節,可以直接使用Hibernate框架,不過第一次用可能會覺得配置比較繁瑣。

Ⅱ 如何用Java實現資料庫查詢

import java.sql.*;
public class MSSQLText
{
public static void main(String args[])
{
String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=Northwind";
String user="sa";//這里替換成你自已的資料庫用戶名
String password="sa";//這里替換成你自已的資料庫用戶密碼
String sqlStr="select CustomerID, CompanyName, ContactName from Customers";
try
{ //這里的異常處理語句是必需的.否則不能通過編譯!
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
System.out.println("類實例化成功!");

Connection con = DriverManager.getConnection(url,user,password);
System.out.println("創建連接對像成功!");

Statement st = con.createStatement();
System.out.println("創建Statement成功!");

ResultSet rs = st.executeQuery(sqlStr);
System.out.println("操作數據表成功!");
System.out.println("----------------!");

while(rs.next())
{
System.out.print(rs.getString("CustomerID") + " ");
System.out.print(rs.getString("CompanyName") + " ");
System.out.println(rs.getString("ContactName"));
}
rs.close();
st.close();
con.close();
}
catch(Exception err){
err.printStackTrace(System.out);
}
}
}

Ⅲ 在Java中如何對資料庫中的數據進行操作

package com.;import java.sql.*;import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;public class BaseDao {
/**
* 創建資料庫連接及關閉
*/
// 打開連接
public static Connection getConnection() {
Connection con = null; /*************************** oracl 的連接 ***************************************/
// try { // Class.forName("oracle.jdbc.driver.OracleDriver");
// con = DriverManager.getConnection(
// "jdbc:oracle:thin:@127.0.0.1:1521:orcl", "bbs", "sa");
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// } catch (SQLException e) {
// e.printStackTrace();
// }
/******************************* sqlerver 的連接 ******************************/
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(
"jdbc:sqlserver://127.0.0.1:1433;databasename=bbs", "sa",
"zhou");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
/*********************************************************************/
return con;
} // 關閉
public static void closeAll(Connection connection,
PreparedStatement pStatement, ResultSet res) {
try {
if (connection != null && (!connection.isClosed())) {
connection.close();
}
if (res != null) {
res.close();
res = null;
}
if (pStatement != null) {
pStatement.close();
pStatement = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
對資料庫增刪改查package com.;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;import com.entity.News;public class NewsDao {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;

/**
* 添加新聞
* @param news
* @return
*/
public boolean newsAdd(News news){
boolean result=false;
String sql="insert into news values(?,?)";
con=BaseDao.getConnection();
try {
pstmt=con.prepareStatement(sql);
pstmt.setString(1, news.getContent());
pstmt.setString(2, FormatTime.newTime());

int i = 0;
i = pstmt.executeUpdate();
if (i > 0)
result = true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
/**
* 修改新聞
* @param news
* @return
*/
public boolean updateNews(News news){
boolean result=false;
con=BaseDao.getConnection();
try {
pstmt=con.prepareStatement("update news set content=? ,writedate=? where newsid=?");
pstmt.setString(1, news.getContent());
pstmt.setString(2, FormatTime.newTime());
pstmt.setInt(3, news.getNewsID());
int i = 0;
i = pstmt.executeUpdate();
if (i > 0)
result = true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
/**
* 刪除新聞
* @param news
* @return
*/
public boolean deleteNews(News news){
boolean result=false;
String sql=String.format("delete from news where newsid=%d", news.getNewsID());
con=BaseDao.getConnection();
try {
pstmt=con.prepareStatement(sql);

int i = 0;
i = pstmt.executeUpdate();
if (i > 0)
result = true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}

/**
* 刪除新聞 重載
* @param newsId
* @return
*/
public boolean deleteNews(int newsId){
boolean result=false;
String sql=String.format("delete from news where newsid=%d", newsId);
con=BaseDao.getConnection();
try {
pstmt=con.prepareStatement(sql);
int i = 0;
i = pstmt.executeUpdate();
if (i > 0)
result = true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
/**
* 查詢所有的新聞
* @return
*/
public List<News> selectAllNews(){
List<News> list=new ArrayList<News>();
String sql="select * from Users";
con=BaseDao.getConnection();
try {
pstmt=con.prepareStatement(sql);
rs=pstmt.executeQuery();
while(rs.next()){
News news=new News();
news.setNewsID(rs.getInt(1));
news.setContent(rs.getString(2));
news.setWriteDate(rs.getString(3));

list.add(news);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
BaseDao.closeAll(rs, pstmt, con);
}
return list;
}
/**
* 查詢單個
* @return
*/
public News selectOneNews(){
News news=new News();
con=BaseDao.getConnection();
try {
pstmt=con.prepareStatement("select top 1 * from news order by newsid desc");
rs=pstmt.executeQuery();
while(rs.next()){
news.setNewsID(rs.getInt(1));
news.setContent(rs.getString(2));
news.setWriteDate(rs.getString(3));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
BaseDao.closeAll(rs, pstmt, con);
}
return news;
}

}
實體類package com.entity;import java.io.Serializable;
public class News implements Serializable{
private int newsID;
private String content;
private String writeDate; public News() {
super();
// TODO Auto-generated constructor stub
} public News(String content, String writeDate) {
super();
this.content = content;
this.writeDate = writeDate;
} public News(int newsID, String content, String writeDate) {
super();
this.newsID = newsID;
this.content = content;
this.writeDate = writeDate;
} public int getNewsID() {
return newsID;
} public void setNewsID(int newsID) {
this.newsID = newsID;
} public String getContent() {
return content;
} public void setContent(String content) {
this.content = content;
} public String getWriteDate() {
return writeDate;
} public void setWriteDate(String writeDate) {
this.writeDate = writeDate;
}
}

Ⅳ java程序是怎麼操作資料庫的(高分懸賞)

Java 實現連接sql server 20002007-12-16 13:28:00.0
第一種:通過ODBC連接資料庫

JAVA語言的跨平台的工作能力(Write Once ,Run Anywhere)、優秀的圖像處理能力(我相信現在沒有那種語言可以超過JAVA在網路上的圖形處理能力)、網路通信功能、通過JDBC資料庫訪問技術等等,讓我們誰都不可否認JAVA語言是SUN公司對於計算機界的一個巨大的貢獻。筆者可以描述這樣一個場景:有一天你上網完全可以不用IE 或者NETSCAPE,上網就像是玩游戲,你可以獲得游戲那麼精美的圖像和互動的感覺,如果你玩過UO,也許你就知道那種感覺了,但是JAVA做成的東西一定會超過UO的,因為不單單是游戲,也不是單單是瀏覽器,如果你願意(要你有錢,有時間,有優秀的JAVA人才)你可以把所有的這一切用Java完全集成出來!!!我不是誇大JAVA的功能,大家可以訪問一下http://www.simchina.net的那個社區程序,你就能找到一種感覺了:相信我沒有說什麼假話 。好了,不說廢話了,現在我向你介紹JAVA的資料庫訪問技術----JDBC資料庫訪問技術(你可千萬不要搞成ODBC了喲!)。

JDBC技術事實上是一種能通過JAVA語言訪問任何結構化資料庫的應用程序介面(API)(Sun這樣說的,我也不知道是不是真的),而且現在的JDBC 3.0據Sun說也能訪問Execel等電子表格程序!

JDBC對於資料庫的訪問有四種方式,我們這里只是介紹兩種:

第一種是通過ODBC做為「橋」(Bridge)對資料庫訪問,第二種是直接對資料庫訪問。

我們先來看看第一種JDBC<-->ODBC訪問的流程:

JDBC Driver Mannager->JDBC<->ODBC橋->ODBC->資料庫客戶機驅動庫->資料庫伺服器->返回查詢結果,在這種訪問中值的我們注意的是雖然JAVA是"Write Once ,Run Anywhere",但是如果通過這種訪問的話,需要客戶端必須設置ODBC和有相應的資料庫客戶機的驅動,當你看了下面的另外一個流程的時候或許你會想:明明下一種更方面,為什麼還要有這個東西的產生!呵呵,因為,未必所有的資料庫伺服器提供商都提供下面的JDBC驅動程序(給JDBC訪問提供相應的介面),所以就有了JDBC<->ODBC Bridge。

接著再讓我們來看看第二種訪問流程:

JDBC Driver Mannager->局部JDBC驅動->客戶端資料庫->資料庫伺服器->返回查詢結果,這種訪問事實上是轉換JDBC調用為相應的資料庫(Oracle, Sybase, Informix, DB2, 和其他的資料庫資料庫管理系統)的客戶端API調用(這么說,不知道大家能不能懂,說簡單點就好像ASP不是通過DSN對資料庫訪問而是通過OLEDB訪問,說道這里我還是不知道大家能不能明白我的意思。哎呀,不要扔雞蛋嘛!),這種方式的訪問需要相應的資料庫提供商提供相應的JDBC驅動程序,但是有一種好處,可以獨立於odbc用於可以隨處可Run的客戶端的瀏覽器中的Applet程序。
我們下面將給大家一個通過JDBC-ODBC橋資料庫訪問的實例,但是在看下面的事例前我想問大家一次:JDK1.3裝了嗎?資料庫驅動裝了嗎(我使用的是SQLserver)?你該沒有使用Linux吧?雖然java支持Linux,但是老兄我可沒有使用Linux喲(這同JAVA的Write Once ,Run Anywhere沒有關系),由於使用了運行於Win下面的ODBC,我建議你看看這篇東西http://www.aspcn.com/showarticle.asp?id=112,否則你要是有了問題,出不了結果那豈不是要怪我(不過欲加之罪,何患無吃... ...),冤枉呀!

哎呀,說了這么多的廢話,還是讓我們來看看到底JDBC的調用吧!既然我們是通過odbc訪問資料庫,所以這個odbc是跑不了的,我們先來設置你的odbc:打開你的odbc數據源->選擇系統dsn(Click加新的dsn-)->接下來輸入選擇資料庫類型、輸入dsn名:、選擇伺服器、連接資料庫的方式、輸入資料庫的登陸用戶和密碼->測試連接,如果測試成功的話,那麼你的dsn就建立好了,我的dsn名為Sqlserver.使用的是sqlserver7.0,以 「sa」登陸,密碼為空。這些東西都是後面要用道的!

好了下面讓我們來看程序代碼: (該代碼已經通過運行)
//###########################################################
//代碼開始
//###########################################################

import java.sql.*;
//載入java數據連接包,java基本所有的資料庫的調用的都在這個東西裡面

public class InsertCoffees {

public static void main(String args[]) {

String url = "jdbc:odbc:sqlserver";
//取得連接的url名,注意sqlserver是dsn名
Connection con;
//實例化一個Connection對象
Statement stmt;
String query = "select * from col_link";
//選擇所有的Col_link表中的數據輸出

try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//載入jdbc-odbc橋驅動

} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
//載入jdbc-odbc橋錯誤
System.err.println(e.getMessage());
//其他錯誤
}

try {

con = DriverManager.getConnection(url, "sa", "");
//資料庫連接

stmt = con.createStatement();
//Create 一個聲明
stmt.executeUpdate("CREATE TABLE col_link (sitename varchar (20) NULL ,siteurl varchar (50) NULL) ");
//執行了一個sql語句生成了一個表col_link的表
stmt.executeUpdate("insert into col_link values('ASP中華網','http://www.aspcn.com')");
stmt.executeUpdate("insert into col_link values('永遠到底有多遠','http://xuankong.com')");
//執行一個insert into語句
stmt.executeUpdate("update col_link set siteurl='http://www.aspcn.com/xuankong/xuankongt.jpg' where siteurl='http://xuankong.com'");
//執行一個update語句,更新資料庫
ResultSet rs = stmt.executeQuery(query);
//返回一個結果集
System.out.println("Col_link表中的數據如下(原始數據)");
//下面的語句使用了一個while循環列印出了col_link表中的所有的數據
System.out.println("站點名 "+" "+"站點地址");
System.out.println("---------------"+" "+"----------------");
while (rs.next()) {
String s = rs.getString("sitename");
String f = rs.getString("siteurl");
//取得資料庫中的數據
System.out.println(s + " " + f);
/*String t = rs.getString(1);
String l = rs.getString(2);
System.out.println(t + " " + l);*/
/*jdbc提供了兩種方法識別欄位,一種是使用getXXX(注意這里的getXXX表示取不同類型欄位的不同的方法)獲得欄位名,
第二種*是通過欄位索引,在這里我把第二種方法注釋了*/
/*你可以訪問這個連接獲得getxxx的用法:http://java.sun.com/docs/books/tutorial/jdbc/basics/_retrievingTable.html*/
}
stmt.close();
con.close();
//上面的語句關閉聲明和連接
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
//顯示資料庫連接錯誤或者查詢錯誤
}
}
}
//###########################################################
//代碼結束
//###########################################################

在上面這個程序中我想你展示了如何使用JDBC-ODBC連接資料庫,使用SQL語句生成一個表,使用SELECT、INSERT 、UPDATE語句取的、插入和更新一個表中的數據,如何通過欄位名和欄位索引訪問資料庫中的東東!我希望你能從上面的代碼真正的學習到一些東西!

發揮你的想像力,設想一下JAVA到底,比如說可以通過資料庫做一個不需要GUI(圖形用戶界面)的聊天室,呵呵,感覺起來就像在DOS環境下打字的聊天室!哈哈!

最後需要說的是筆者的調試上面程序的環境:WIN2000 , JDK1.3,MS SQLSERVER編輯軟體:EDITPLUS 2.01a(這最後的東西可不是廢話,雖然早就了一些專業的JAVA開發工具,但是筆者建議JAVA初學者使用文本軟體開發JAVA程序)

第二種:直接用jdbc訪問資料庫

(1) 該實例已經運行通過

jsp連接Sql Server7.0/2000資料庫
testsqlserver.jsp如下:
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*"%>
<html>
<body>
<%Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs";
//pubs為你的資料庫的
String user="sa";
String password="";

Connection conn= DriverManager.getConnection(url,user,password);
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql="select * from test";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()) {%>
您的第一個欄位內容為:<%=rs.getString(1);%>
您的第二個欄位內容為:<%=rs.getString(2);%>
<%}%>
<%out.print("資料庫操作成功,恭喜你");%>
<%rs.close();
stmt.close();
conn.close();

%>
</body>
</html>

(2)java訪問sqlserver伺服器

第一步:安裝jdbc

點擊SQL Server for JDBC驅動程序安裝程序setup.exe(可以到微軟網站下載 http://msdn.microsoft.com/library/default.asp?rul=/downloads/list/sqlserver.asp下載)

第二步:設置系統變數classpath

假設SQL Server for JDBC 驅動程序安裝在d:\jdbc\,則classpath應該設置如下:

classpath:=.;…;d:\jdbc\lib; d:\jdbc\lib\mssqlserver.jar; d:\jdbc\lib\msutil.jar; d:\jdbc\lib\msbase.jar;

注意:設置時要在最前面的點號和分號

第三步:編輯java程序並且運行

實例1如下:

//import com.microsoft.*;

//注意:在java與sql server 連接時不需要這個包,其他書上說這個包是必需的,這個問題有待進一步討論

import java.sql.*;

import java.net.URL;

class insert

{

public static void main(String[] args)

{

String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=northwind";

String query="select * from categories";

String query1="insert categories values(10,'Hanbao','Sweet')";

String query2="insert categories values(11,'Naicha','Coffee taste')";

try

{

Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");

Connection con=DriverManager.getConnection(url,"sa","739555");

Statement stmt=con.createStatement();

stmt.executeUpdate(query1);

stmt.executeUpdate(query2);

stmt.close();

con.close();

}

catch(SQLException ex)

{

}

catch(java.lang.Exception ex)

{

ex.printStackTrace();

}

}

}

實例2如下:

//import com.microsoft.*;

//注意:在java與sql server 連接時不需要這個包,其他書上說這個包是必需的,這個問題有待進一步討論

import java.sql.*;

import java.net.URL;

class java2sqlserver

{

public static void main(String[] args)

{

String url="jdbc:microsoft:sqlserver://localhost:1433;User=sa;Password=739555;DatabaseName=northwind";

String query="Select * From Categories";

try

{

Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");

//DriverManager.setLogStream(System.out);

Connection con=DriverManager.getConnection(url);

checkForWarning(con.getWarnings());

Statement stmt=con.createStatement();

ResultSet rs=stmt.executeQuery(query);

dispResultSet(rs);

rs.close();

stmt.close();

con.close();

}

catch(SQLException ex)

{

System.out.println(ex.toString()+"----SQLException caught----");

while(ex!=null)

{

System.out.print("SQLState:"+ex.getSQLState());

System.out.print("Message:"+ex.getMessage());

System.out.print("Vendor:"+ex.getErrorCode());

ex=ex.getNextException();

System.out.println("");

}

}

catch(java.lang.Exception ex)

{

ex.printStackTrace();

}

}

private static boolean checkForWarning(SQLWarning warn)

{

boolean rc=false;

if(warn!=null)

{

System.out.println("----Warning----");

rc=true;

while(warn!=null)

{

System.out.print("SQLState:"+warn.getSQLState());

System.out.print("Message:"+warn.getMessage());

System.out.print("Vendor:"+warn.getErrorCode());

System.out.println("");

warn=warn.getNextWarning();

}

}

return rc;

}

private static void dispResultSet(ResultSet rs) throws SQLException

{

int i;

ResultSetMetaData rsmd=rs.getMetaData();

int numCols=rsmd.getColumnCount();

for(i=1;i<=numCols;i++)

{

if(i>1) System.out.print(", ");

System.out.print(rsmd.getColumnLabel(i));

}

System.out.println("");

boolean more=rs.next();

while(more)

{

for(i=1;i<numCols;i++)

{

if(i<1) System.out.print(", ");

System.out.println(rs.getString(i));

}

System.out.println("");

more=rs.next();

}

}

//System.out.println("Hello World!");

}

以上兩個實例筆者已經通過運行!

Ⅳ 怎麼使用JAVA連接資料庫

1、首先我們先建好資料庫,然後建立好程序的目錄,因為是適用於初學者的,所以就建立一個簡單的java project,如圖。

Ⅵ java操作資料庫的方式有哪些

JDBC是java資料庫連接技術的簡稱,它提供了連接各種資料庫的能力,這便使程序的可維護性和可擴展性大大的提高了.JDBC連接資料庫常見的驅動方式有兩種,一種是jdbc-odbc即橋連另外一種是純java驅動.一般在做java開發的時候用第二種.so前一種我就不說了,純java驅動方式連接步驟如下:

1.先把一個jdbc的jar包導入到項目(用MyEclipse開發)的lib中.

2.代碼如下:

[c-sharp]view plain

  • importjava.sql.*;

  • /**

  • *連接資料庫幫助類

  • *@authorAdministrator

  • *

  • */

  • publicclassBaseDao{

  • ="com.microsoft.sqlserver.jdbc.SQLServerDriver";

  • privatestaticfinalStringURL="jdbc:sqlserver://localhost:1433;DatabaseName=LibraryManageSystem";

  • ="sa";

  • ="sa";

  • /**

  • *連接資料庫

  • *@return資料庫連接對象

  • *@throwsClassNotFoundException

  • *@throwsSQLException

  • */

  • publicConnectiongetConn()throwsClassNotFoundException,SQLException{

  • Class.forName(DRIVER);

  • Connectionconn=DriverManager.getConnection(URL,USERNAME,PASSWORD);

  • returnconn;

  • }

  • /**

  • *釋放資源

  • *@paramconn

  • *@parampstmt

  • *@paramrs

  • *@throwsSQLException

  • */

  • publicvoidcloseAll(Connectionconn,PreparedStatementpstmt,ResultSetrs)throwsSQLException{

  • if(rs!=null){

  • rs.close();

  • }

  • if(pstmt!=null){

  • pstmt.close();

  • }

  • if(conn!=null){

  • conn.close();

  • }

  • }

  • /**

  • *執行SQL語句,可以進行增、刪、改的操作

  • *@paramsql

  • *@return影響條數

  • *@throwsClassNotFoundException

  • *@throwsSQLException

  • */

  • publicintexecuteSQL(Stringsql)throwsClassNotFoundException,SQLException{

  • Connectionconn=this.getConn();

  • PreparedStatementpstmt=conn.prepareStatement(sql);

  • intnumber=pstmt.executeUpdate();

  • this.closeAll(conn,pstmt,null);

  • returnnumber;

  • }

  • }

  • 從代碼知道首先吧jdbc驅動類裝載java虛擬機中,即Class.forName(DRIVER);其次載入驅動並建立於資料庫的連接Connection conn = DriverManager.getConnection(URL,USERNAME,PASSWORD);;然後發送SQL語句並的到結果集.之後處理結果,最後要關閉資料庫的連接,釋放資源.當然我說的這樣連接資料庫的方式使用的軟體是sql和MyEclipse.

    使用配置文件來連接資料庫,當然這樣的連接需要進行一些配置.其實這樣的連接用專業術語來說就是連接池,連接池是負責分配管理和釋放資料庫連接.它允許用用程序重復使用一個現有的資料庫連接不再重復建立連接.釋放空閑時間超過最大空閑時間的資料庫連接以避免因為沒有釋放資料庫而引起的資料庫遺漏.

    連接池的創建分為以下幾個步驟:1.配置context.xml文件 這個文件是伺服器(指tomcat)的一個conf文件夾中,拷貝出來放入項目的lib文件夾中,具體配置如下:

    [c-sharp]view plain

  • <Resourcename="jdbc/book"auth="Container"type="javax.sql.DataSource"

  • maxActive="100"maxIdle="20"maxWait="100"username="sa"password="sa"

  • driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"

  • url="jdbc:sqlserver://localhost:1433;dataBaseName=book"

  • />在config.xml文件中加入Resource標簽,然後對資料庫信息進行配置,當然這個資料庫指的也是sqlserver有疑問可以qq757966892聯系

  • 之後把資料庫的驅動包,這里指的是sql2005的包放入伺服器的lib中,這樣以後如果在你自己的機子上都不用在重新導入這個包了.

    然後就是從MyEclipse中取得這樣的連接從而對資料庫進行一些操作具體代碼如下:

    [c-sharp]view plain

  • packageweb.login.;

  • importjava.sql.Connection;

  • importjava.sql.PreparedStatement;

  • importjava.sql.ResultSet;

  • importjavax.naming.Context;

  • importjavax.naming.InitialContext;

  • importjavax.sql.DataSource;

  • publicclassBaseDao{

  • protectedConnectionconn;

  • protectedPreparedStatementps;

  • protectedResultSetrs;

  • protectedStringsql;

  • publicConnectiongetConn(){

  • try{

  • Contextcontext=newInitialContext();

  • DataSourceds=(DataSource)context.lookup("java:comp/env/jdbc/user");

  • returnds.getConnection();

  • }catch(Exceptione){

  • e.printStackTrace();

  • returnnull;

  • }

  • }

  • publicvoidcloseAll(Connectionconn,PreparedStatementps,ResultSetrs){

  • try{

  • if(rs!=null){

  • rs.close();

  • rs=null;

  • }

  • if(ps!=null){

  • ps.close();

  • ps=null;

  • }

  • if(conn!=null){

  • conn.close();

  • conn=null;

  • }

  • }catch(Exceptione){

  • e.printStackTrace();

  • }

  • }

  • }

  • 之後便可以建立業務類從而對資料庫進行操作.

Ⅶ JAVA如何實現資料庫的批處理操作

批量數據進入資料庫使用addBatch()和executeBatch()方法
PreparedStatement.addBatch(); ...... PreparedStatement.executeBatch();需要注意的是一次最多不要超過50條:1.因為插入的時候資料庫已經鎖定,然而若是一次性插入太多會造成其他業務的等待。2.會造成內存的溢出
舉例:

PreparedStatement pst = (PreparedStatement) con.prepareStatement("insert into ***** values (?,'***')"); for (int i = 0; i < 10000; i++) { pst.setInt(1, i); // 把一個SQL命令加入命令列表 pst.addBatch(); } // 執行批量更新 pst.executeBatch(); // 語句執行完畢,提交本事務 con.commit();

Ⅷ java中使用JDBC完成資料庫操作的基本步驟是什麼

創建一個以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對資料庫中數據的操作

這個就看你的資料庫設計了,比如說兩個資料庫,一個是存種類(酒,菜。。),一個是存種類裡面的分類(白酒,啤酒。。),然後在項目中鏈接資料庫進行操作