導航:首頁 > 編程語言 > java文件的寫入資料庫

java文件的寫入資料庫

發布時間:2022-04-25 23:50:42

java將txt文檔內容寫入資料庫

首先你要在資料庫建表,假設表是 info 欄位分別是id , name, age, score ,mail
表 info 對應一個類Info ,屬性有 int id; String name; int age; int score ;String mail
構造方法你會寫的
下面是寫入資料庫代碼:
Class.forName("org.sqlite.JDBC");//載入資料庫驅動
Connection conn = DriverManager.getConnection("jdbc:sqlite:info.s3db");//鏈接資料庫,info.s3db是資料庫名字,我用的是sqlite.
PreparedStatement ps = conn.PreparedStatement("insert into info values(?,?,?,?)");//創建語句對象
ps.setInt(1,info.getId());
ps.setString(2,info.getName());
。。。。以此類推
ps.executeUpdate();
這樣就插入到資料庫了。你可以到表裡看看
至於輸出成績的話 你要寫方法了。。。

㈡ 怎樣用java把文本文檔內容寫入到資料庫裡面

大體思路是:用流讀取文本中的內容,存到一個位元組數組里,然後把這個數組保存到庫里,庫里對應的欄位類型是 blob

㈢ 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() ;
}
}

(3)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中怎樣將String類型的數據寫入資料庫

需要下載好的東西:MySQL-connector-java-5.0.3-bin.jar

在配置好MyEclipse的JSP基本環境後

開啟apmserv後,配置MyEclipse的鏈接環境:window-open perspection-MyEclipse database exp...新建一個鏈接,url處:jdbc:MySQL:(MySQL資料庫鏈接),username和password是登錄資料庫的(不要弄錯了).在finish前可以嘗試鏈接,鏈接成功-finish.鏈接失敗注意看提示,一般是url的錯誤,多多嘗試.我用apmserv的url是jdbc:MySQL:127.0.0.1/(資料庫名)

之後在新建的web工程下,在WEB-INF\lib中improt-general-file system-選擇MySQL-connector-java-5.0.3-bin.jar所在的文件夾-finish

使用下面的代碼,可以測試鏈接,注意更改使用的資料庫名,數據等

JDBCHelloWorld.java
import java.sql.SQLException;
/**
* 第一個 JDBC 的 HelloWorld 程序, 資料庫訪問 MySQL.
*/
public class JDBCHelloWorld {
/**
* @param args
* @throws SQLException
*/
public static void main(String[] args) throws SQLException {
// 1. 注冊驅動
try {
Class.forName("com.MySQL.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}// MySQL 的驅動
// 2. 獲取資料庫的連接
java.sql.Connection conn = java.sql.DriverManager.getConnection(
"jdbc:MySQL://localhost/test?useUnicode=true&characterEncoding=GBK", "root", null);
// 3. 獲取表達式
java.sql.Statement stmt = conn.createStatement();
// 4. 執行 SQL
java.sql.ResultSet rs = stmt.executeQuery("select * from user"); //這里是你要執行的SQL
// 5. 顯示結果集裡面的數據
while(rs.next()) {
System.out.println(rs.getInt(1));
System.out.println(rs.getString("username"));
System.out.println(rs.getString("password"));
System.out.println();
}
// 6. 釋放資源
rs.close();
stmt.close();
conn.close();
}
}

㈤ java文件路徑怎麼存入資料庫

直接讀寫文件,再把讀出來的文件內容格式化成json,再用jdbc、mybatis或者其他框架將json數據存入資料庫。

㈥ 如何使用Java解析文件並存入資料庫

怎樣的文件、哪種資料庫、怎樣的資料庫的格式
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

㈦ 怎樣用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把TXT文件導入資料庫中

1、java i/o讀取txt文本
2、使用實體類封裝或使用list、map等封裝讀取到的數據
3、jdbc

txt文本要保證符合一定的格式,如每個欄位間已特定字元分割。

㈨ 怎麼用java將一個文件直接寫入到sqlserver資料庫中

java中使用jdbc連接sql server資料庫步驟:
1.JDBC連接SQL Server的驅動安裝 ,前兩個是屬於資料庫軟體,正常安裝即可(注意資料庫登陸不要使用windows驗證)
<1> 將JDBC解壓縮到任意位置,比如解壓到C盤program files下面,並在安裝目錄里找到sqljdbc.jar文件,得到其路徑開始配置環境變數
在環境變數classpath 後面追加 C:\Program Files\Microsoft SQL Server2005 JDBC Driver\sqljdbc_1.2\enu\sqljdbc.jar
<2> 設置SQLEXPRESS伺服器:
a.打開SQL Server Configuration Manager -> SQLEXPRESS的協議 -> TCP/IP
b.右鍵單擊啟動TCP/IP
c.雙擊進入屬性,把IP地址中的IP all中的TCP埠設置為1433
d.重新啟動SQL Server 2005服務中的SQLEXPRESS伺服器
e.關閉SQL Server Configuration Manager
<3> 打開 SQL Server Management Studio,連接SQLEXPRESS伺服器, 新建資料庫,起名字為sample
<4> 打開Eclipse
a.新建工程-> Java -> Java project,起名為Test
b.選擇eclipse->窗口->首選項->Java->installed JRE 編輯已經安裝好的jdk,查找目錄添加sqljdbc.jar
c.右鍵單擊目錄窗口中的Test, 選擇Build Path ->Configure Build Path..., 添加擴展jar文件,即把sqljdbc.jar添加到其中
<5> 編寫Java代碼來測試JDBC連接SQL Server資料庫
import java.sql.*;
public class Test {
public static void main(String[] srg) {
//載入JDBC驅動
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
//連接伺服器和資料庫sample
String dbURL = "jdbc:sqlserver://localhost:1433; DatabaseName=sample";
String userName = "sa"; //默認用戶名
String userPwd = "123456"; //密碼

Connection dbConn;
try {
Class.forName(driverName);
dbConn = DriverManager.getConnection(dbURL, userName, userPwd);
System.out.println("Connection Successful!"); //如果連接成功 控制台輸出
} catch (Exception e) {
e.printStackTrace();
}
}
}

執行以後就可以連接到sample資料庫了。

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

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

閱讀全文

與java文件的寫入資料庫相關的資料

熱點內容
銀河麒麟字體庫存在哪個文件夾 瀏覽:956
魔獸加丁伺服器的航空叫什麼 瀏覽:152
花冠改裝案例哪個app多 瀏覽:515
成績單app哪個好用 瀏覽:140
北美程序員vs國內程序員 瀏覽:181
php解析xml文檔 瀏覽:121
石墨文檔APP怎麼橫屏 瀏覽:185
牆主鋼筋加密和非加密怎麼看 瀏覽:144
金山區文件夾封套定製 瀏覽:708
soho程序員 瀏覽:672
java位元組截取 瀏覽:525
php提交作業 瀏覽:815
房產還沒解壓可以辦理贈予嗎 瀏覽:224
java毫秒轉分鍾 瀏覽:753
模式識別中文pdf 瀏覽:774
c語言平均數字編譯錯誤 瀏覽:171
單片機算交流 瀏覽:45
php自適應網站 瀏覽:467
2b2t伺服器怎麼獲得許可權 瀏覽:816
c語言javaphp 瀏覽:804