當前位置:首頁 » 操作系統 » java文件存到資料庫

java文件存到資料庫

發布時間: 2023-05-30 04:12:53

java怎樣將讀取數據寫入資料庫

Java可以使用JDBC對資料庫進行讀寫。JDBC訪問一般分為如下流程:

一、載入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類中。

二、提供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:字元編碼方式。

三、創建資料庫的連接

要連接資料庫,需要向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() ;
} 納核

四、創洞團掘建一個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(? , ?)}") ;

五、執行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) ;

六、處理結果 兩種情況:
1、執行更新返回的是本次操作影響到的記錄數。

2、執行查詢返回的結果是一個ResultSet對象。

ResultSet包含符合SQL語句中條件的所有行,並且它通過一套get方法提供了對這些行中數據的訪問。

使用結果集(ResultSet)對象的訪問方法獲取數據:

while(rs.next()){

String name = rs.getString("name") ;

String pass = rs.getString(1); // 此方法比較高效(列是從左到右編號的,並且從列1開始)
}

七、關閉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() ;
}
}

(1)java文件存到資料庫擴展閱讀

樣例

package first;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.concurrent.Executors;

import java.util.concurrent.ScheledExecutorService;

import java.util.concurrent.TimeUnit;

public class lianjie {

public static void main(String[] args) {

Runnable runnable = new Runnable() {

public void run() {

//聲明Connection對象

Connection con;

//驅動程序名

String driver1 = "com.microsoft.sqlserver.jdbc.SQLServerDriver";

//URL指向要訪問的資料庫名

String url1 = "jdbc:sqlserver://IP地址和埠號;DateBaseName=資料庫名";

//MySQL配置時的用戶名

String user1 = "user";

//MySQL配置時的密碼

String password1 = "user";

//聲明Connection對象

Connection con1;

//驅動程序名

String driver2 = "com.microsoft.sqlserver.jdbc.SQLServerDriver";

//URL指向要訪問的資料庫名

String url2 = "jdbc:sqlserver://IP地址和埠號;DateBaseName=資料庫名";

//MySQL配置時的用戶名

String user2 = "user";

//MySQL配置時的密碼

String password2 = "user";

//遍歷查詢結果集

try {

//載入驅動程序

Class.forName(driver1);

//1.getConnection()方法,連接MySQL資料庫!!

con = DriverManager.getConnection(url1,user1,password1);

if(!con.isClosed())

System.out.println("成功連接到資料庫!");

try {

//載入驅動程序

Class.forName(driver2);

//1.getConnection()方法,連接MySQL資料庫!!

con1 = DriverManager.getConnection(url2,user2,password2);

if(!con1.isClosed())

System.out.println("成功連接到資料庫!");

//2.創建statement類對象,用來執行SQL語句!!

Statement statement = con.createStatement();

//要執行的SQL語句

String sql = "use 資料庫名 select * from 表名";

//3.ResultSet類,用來存放獲取的結果集!!

ResultSet rs = statement.executeQuery(sql);

//要執行的SQL語句

String sql1 = "use tiantiana insert into Table_1(tiantian,qiqi,yuyu)VALUES(?,?,?)";

//3.ResultSet類,用來存放獲取的結果集!!

PreparedStatement pst = con1.prepareStatement(sql1);

System.out.println ("tiantian"+"/t"+"qiqi"+"/t"+"yuyu");

while(rs.next()){

System.out.print(rs.getString(1));

System.out.print(rs.getString(2));

System.out.print(rs.getString(3));

pst.setString(1,rs.getString(1));

pst.setString(2,rs.getString(2));

pst.setString(3,rs.getString(3));

pst.executeUpdate();

}

pst.close();

rs.close();

//2.創建statement類對象,用來執行SQL語句!!

Statement statement1 = con.createStatement();

//要執行的SQL語句

String sql2 = "use 資料庫名 select * from 表名";

//3.ResultSet類,用來存放獲取的結果集!!

ResultSet rs1 = statement1.executeQuery(sql2);

//要執行的SQL語句

String sql3 = "use tiantiana insert into Table_2(tiantian1,qiqi1,yuyu1)VALUES(?,?,?)";

//3.ResultSet類,用來存放獲取的結果集!!

PreparedStatement pst1 = con1.prepareStatement(sql3);

System.out.println ("tiantian1"+"/t"+"qiqi1"+"/t"+"yuyu1");

while(rs1.next()){

System.out.print(rs1.getString(1));

System.out.print(rs1.getString(2));

System.out.print(rs1.getString(3));

pst1.setString(1,rs1.getString(1));

pst1.setString(2,rs1.getString(2));

pst1.setString(3,rs1.getString(3));

pst1.executeUpdate();

}

//關閉鏈接

rs1.close();

pst.close();

con1.close();

con.close();

} catch(ClassNotFoundException e) {

//資料庫驅動類異常處理

System.out.println("對不起,找不到驅動程序!");

e.printStackTrace();

} catch(SQLException e) {

//資料庫連接失敗異常處理

e.printStackTrace();

}catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

}finally{

System.out.println("資料庫數據成功獲取!!");

}

} catch(ClassNotFoundException e) {

//資料庫驅動類異常處理

System.out.println("對不起,找不到驅動程序!");

e.printStackTrace();

} catch(SQLException e) {

//資料庫連接失敗異常處理

e.printStackTrace();

}catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

}finally{

System.out.println("資料庫數據成功獲取!!");

}

}

};

ScheledExecutorService service = Executors

.();

// 第二個參數為首次執行的延時時間,第三個參數為定時執行的間隔時間

service.scheleAtFixedRate(runnable, 10, 60*2, TimeUnit.SECONDS);

}

}

Ⅱ 用java代碼把txt文檔中資料導入到資料庫

BufferedReader input;
try {
String s = new String();
input = new BufferedReader(new FileReader("f:\\123.txt"));
while ((s = input.readLine()) != null) { // 判斷是否讀到了最後一行
String info[] = s.split(" ");
System.out.println( info[0] + " " + info[1] + " " + info[2] );
}
input.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
把info[0] + " " + info[1] + " " + info[2] 這三個值放在insert語句里就行了 經過測試

Ⅲ JAVA中存文件到ORACLE資料庫里怎麼做

參考代碼如下:
public class InsertBlobData {
Connection con = null;

/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
InsertBlobData data = new InsertBlobData();
data.insertBlogInfo("002jpg", "sdsdfdf", "2007-02-12", "002.jpg");
}
public void insertBlogInfo(String jmzh, String xm, String smsj,
String fileName) throws Exception {
// try {
con = ConnectionPoliceFactory.getFactory().getConnection();
// } catch (ClassNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// 處理事務
boolean defaultCommit = con.getAutoCommit();
con.setAutoCommit(false);
Statement st = con.createStatement();
// 插入一個空對象
st.executeUpdate("insert into ksren_txxx(jmzh,xm,smsj,txsj) values('"
+ jmzh + "','" + xm + "',to_date('" + smsj
+ "','yyyy-mm-dd'),empty_blob())");
// 用for update方式鎖定數據行
ResultSet rs = st
.executeQuery("select txsj from ksren_txxx where jmzh='"
+ jmzh + "' and xm='" + xm + "' for update");
if (rs.next()) {
// 得到java.sql.Blob對象,然後Cast為oracle.sql.BLOB
oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob(1);
// 到資料庫的輸出流
OutputStream outStream = blob.getBinaryOutputStream();
// 這里用一個文件模擬輸入流
InputStream fin = new FileInputStream(new File(fileName));
// 將輸入流寫到輸出流
byte[] b = new byte[blob.getBufferSize()];
int len = 0;
while ((len = fin.read(b)) != -1) {
outStream.write(b, 0, len);
// blob.putBytes(1,b);
}
// 依次關閉(注意順序)

fin.close();
outStream.flush();
outStream.close();
con.commit();
/* 恢復原提交狀態 */
con.setAutoCommit(defaultCommit);
con.close();

}
}
}

Ⅳ 用java怎樣把數據存到資料庫中

只能寫個大概的,鋒滾要寫銀祥余數據到資料庫中,先得在資料庫中建庫,庫里建表,表裡建欄位,然後java里建立資料庫連接,用SQL語言寫數宴旦據到表中的欄位。

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

//String url="jdbc:microsoft:sqlserver://localhost:1433;=資料庫名"; //7.0、2000

String url="jdbc:sqlserver://localhost:1433;=資料庫名"; //2005、Connection conn=null;

conn= .(url,用戶名,密碼);

pst=null;

pst=conn.("Insert Into grade(表名) Values (?)");

pst.setInt(1,你要寫的整弄數據);

//pst.setString(2,你要寫的字元串數據);

pst.addBatch();

pst.();

Ⅳ JAVA語言寫文件存取,存到ORACLE資料庫里怎麼寫

package com.jspdev.ch13;
import com.jspdev.util.*;
import java.sql.*;
import javax.sql.*;
import java.io.*;
import oracle.jdbc.driver.OracleResultSet;
import oracle.sql.BLOB;
public class BlobBean
{

Connection conn ;
/**
*構造方法,創建Connection對象,並且在資料庫中添加一個表。
*/
public BlobBean()throws Exception
{

DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
conn = DriverManager.getConnection("jdbc:oracle:thin:[email protected]:1521:hellking", "system", "manager");
// conn.createStatement().execute("create table blobtable(blobvalue blob)");
}

/**
*寫入Blob數據到資料庫
*/
public void addBlob(String fileName)throws Exception
{

conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
stmt.execute("insert into blobtable values (empty_blob())");
ResultSet rset = stmt.executeQuery("SELECT blobvalue FROM blobtable FOR UPDATE");
BLOB blob = null;
while (rset.next()) {
blob = ((OracleResultSet) rset).getBLOB(1);
System.out.println(blob.length());
}
File binaryFile = new File(fileName);
System.out.println(fileName+"'s length = " + binaryFile.length());
FileInputStream instream = new FileInputStream(binaryFile);
OutputStream outstream = blob.getBinaryOutputStream();
int chunk = blob.getChunkSize();
System.out.println("chunk size = " + chunk);
byte[] buffer = new byte[chunk];
int length = -1;
while ((length = instream.read(buffer)) != -1)
outstream.write(buffer, 0, length);
instream.close();
outstream.close();
conn.commit();

}

Ⅵ java如何將圖片保存在資料庫中(java保存圖片到本地)

一般都是這樣的,就是在你伺服器有一個專門放置圖片的文件夾,然後資料庫保存的是你伺服器圖片的路徑。需要用的時候就去資料庫裡面取路徑。得到路徑以後你蔽哪想怎麼處理圖片是你的事情了。

至於如何去資料庫取路徑這個就是簡單的db操作。

載入驅動類:

Class.forName(DBDriver);

獲取連接:

Connectionconn=.(url,username,password);

創建操作對象:

stmt=con.(sql);

執行操作:

ResultSetrs=stmt.();

遍歷賣畢結果:

Listlist=newArrayList();

while(rs.next()){

//具體操作,通常用rs.getString(name)取值

Imageimg=newImage();//圖片類對應你資料庫中圖片表格

img.setSrc(rs.getString("src"));//假設你資料庫中image表中圖片地址欄位是src

list.add(img);

}

記得關閉資源:

rs.close();

stmt.close();

con.close();

看你的意思是已經中並芹取出來了不知道怎麼顯示:

你取出來之後可以把圖片放在一個list裡面然後去頁面上遍歷這個list

大致應該是這樣

Ⅶ 怎樣用Java實現從文本文檔中讀取數據並存入資料庫

不知道你要什麼樣的文本,文本中的內容是否是有格式的:

這里提供下思路,供參考:
1.文本文件,基本上式字元格式的了,可以用Readerio流
2.如果是格式化的文本,可以按數據的長度讀取,readIntreadByte...
3.保存到資料庫當然用JDBC了,如果你讀取出來封裝成POJO了,也可以選擇OM框架



importjava.io.BufferedReader;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.io.InputStreamReader;

/**
*文件讀取和寫入資料庫
*@author樊雲升
*
*/
publicclassFilesReader{

publicFilesReader(){

}

/**
*讀取文件內容
*@paramFILE
*@return
*/
publicStringre_content(StringFILE){
Stringcontent="";
try{
BufferedReaderbufRead=newBufferedReader(newInputStreamReader(newFileInputStream(FILE)));
Stringstr;
while((str=bufRead.readLine())!=null){
content+=str+" ";
}
}catch(IOExceptionioe){
ioe.printStackTrace();
}
returncontent;
}

/**
*將特定字元寫入資料庫中(原來我寫的是重寫文件,你這里這里將content寫入資料庫就OK)
*@parampath
*@return
*/
publicbooleanwriteFile(Stringcontent){
try{
//資料庫寫入代碼
}catch(Exceptione){
out.close();
returnfalse;
}
returntrue;
}

publicstaticvoidmain(String[]args){
Stringcontent=newFilesReader().re_content("D:\AJAX.htm");
newFilesReader().writeFile(content);
}

}

Ⅷ 在java中如何將數組里的數據存入資料庫呢

保存位元組數組到資料庫分兩步:
第一、利用FileInputStream.read(byte[])方法把內容讀取到byte[]數組中,比如圖片是由二進制數組成的,就可以定義為一個位元組數組。
第二、在資料庫中對應記錄欄位應該設置為blob類型,這樣就能夠順利保存了
事例代碼如下:
PreparedStatement stmt = connection.generatePreparedStatement("INSERT INTO ... ");
stmt.setBytes(1, yourByteArray);

其中,yourByteArray是你讀出來的字元數組。

Ⅸ java往資料庫存儲大文件

你好。請問什麼資料庫。oracle如下

資料庫中提供了兩種欄位類型 Blob 和 Clob 用於存儲大型字元串或二進制數據(如圖片)。察殲

Blob 採用單位元組存儲,適合保存二進制數據,如圖片文件。
Clob 採用多位元組存儲,適合保存大型文本數據。

首先創建一個空 Blob/Clob 欄位,再從這個圓敏空 Blob/Clob欄位獲取游標,例如下面的代碼:

PreparedStatement ps = conn.prepareStatement( " insert into PICTURE(image,resume) values(?,?) " );
// 通過oralce.sql.BLOB/CLOB.empty_lob()構造空Blob/Clob對象
ps.setBlob( 1 ,oracle.sql.BLOB.empty_lob());
ps.setClob( 2 ,oracle.sql.CLOB.empty_lob());

ps.excuteUpdate();
ps.close();

// 再次對讀出Blob/Clob句柄
ps = conn.prepareStatement( " select image,resume from PICTURE where id=? for update " );
ps.setInt( 1 , 100 );

ResultSet rs = ps.executeQuery();
rs.next();

oracle.sql.BLOB imgBlob = (oracle.sql.BLOB)rs.getBlob( 1 );
oracle.sql.CLOB resClob = (oracle.sql.CLOB)rs.getClob( 2 );

// 將二橘沒枝進制數據寫入Blob
FileInputStream inStream = new FileInputStream( " c://image.jpg " );
OutputStream outStream = imgBlob.getBinaryOutputStream();

byte [] buf = new byte [ 10240 ];
int len;
while (len = inStream.read(buf) > 0 ) {
outStream.write(buf, 0 ,len);
}
inStream.close();
outStream.cloese();

// 將字元串寫入Clob
resClob.putString( 1 , " this is a clob " );

// 再將Blob/Clob欄位更新到資料庫
ps = conn.prepareStatement( " update PICTURE set image=? and resume=? where id=? " );
ps.setBlob( 1 ,imgBlob);
ps.setClob( 2 ,resClob);
ps.setInt( 3 , 100 );

ps.executeUpdate();
ps.close();

Ⅹ java如何里將文件存到資料庫中

java要實現將文件存到資料庫中的話,你可以在資料庫中使用blob類型,然後使用IO操作保存為位元組類型,這樣就可以進行傳輸和下載

熱點內容
scratch少兒編程課程 發布:2025-04-16 17:11:44 瀏覽:639
榮耀x10從哪裡設置密碼 發布:2025-04-16 17:11:43 瀏覽:368
java從入門到精通視頻 發布:2025-04-16 17:11:43 瀏覽:84
php微信介面教程 發布:2025-04-16 17:07:30 瀏覽:310
android實現陰影 發布:2025-04-16 16:50:08 瀏覽:793
粉筆直播課緩存 發布:2025-04-16 16:31:21 瀏覽:344
機頂盒都有什麼配置 發布:2025-04-16 16:24:37 瀏覽:212
編寫手游反編譯都需要學習什麼 發布:2025-04-16 16:19:36 瀏覽:812
proteus編譯文件位置 發布:2025-04-16 16:18:44 瀏覽:366
土壓縮的本質 發布:2025-04-16 16:13:21 瀏覽:592