讀取文件寫入資料庫
直接運行.sql
SQL Server Management Studio
New Query
把sql文件拖入新打開的新建查詢頁面里
Ⅱ asp讀取txt文件並寫入資料庫
可以用fSO逐行讀取
<body>
<%
set fso=server.CreateObject("Scripting.FileSystemObject")
Set txtFile=fso.OpenTextFile(Server.MapPath("text.txt"))
While Not txtFile.AtEndOfStream
Response.Write "<center>" & txtFile.ReadLine & "</center><br>"
。。寫入資料庫
Wend
txtFile.Close
%>
</body>
也可以 直接連接資料庫,從文本中直接讀取
insert into tbl select * OPENROWSET('MICROSOFT.JET.OLEDB.4.0', 'Text;HDR=no;Delimited="::";DATABASE=d:\',tmp#txt)
另外還可以用BCP導入文本到資料庫
類似的樣式:
EXEC master..xp_cmdshell 』bcp "dbname..tablename" in c:「DT.txt -c -Sservername -Usa -Ppassword』
僅供參考,具體寫法請查資料,注意路徑和文件名
Ⅲ php怎麼讀取txt文本內容存入mysql資料庫
這個要看你的txt 裡面是不是按資料庫欄位方式寫的如果是就好辦,我是這樣做,我用txt添加的是郵件地址
每行只要求一個地址
//上傳txt文本
if($_FILES['text']['name']){
$path='../upload';
if(!file_exists($path)){
mkdir($path);
}
if(!is_dir($path)){
mkdir($path);
}
$p=strrchr($_FILES['text']['name'],'.');
if(preg_match("/txt/",$p)){
$file=$path.'/'.date('Ymd').time().$p;
move_uploaded_file($_FILES['text']['tmp_name'],$file);
$get=fopen($file,'r');
$j=0;
while (!feof($get)){ //循環讀取每一行
$row=fgets($get);
$row=str_replace(' ','',$row);
$rowa=preg_match("/\@/",$row);
$sql="INSERT INTO `address`(`address`,`timees`,`data`)VALUES('".$rowa."','0',1)";
$db->guery($sql);
$j++;
}
}
echo"<script>alert('已經添加$j條');history.back();</script$amp;>quot;$;
}
}else{
echo"<script>alert('選擇正確添加方式 ');history.back();</script$amp;>quot;$;
}
fclose($get);
Ⅳ 怎樣把大量的數據通過txt文件直接導入到資料庫中
首先資料庫存儲數據有自己的格式:基本數據類型、二進制。。
怎麼存儲文件形式的數據?
1、針對txt文件,讀取文本內容,資料庫欄位設置數據類型text,將讀取的文本內容存入資料庫。
2、轉化為二進制存入資料庫,讀取文件,轉化為二進制流,資料庫欄位設置bit,之後將二進制數據存入資料庫,
3、將txt文件保存伺服器制定目錄下,在資料庫中存儲txt的絕對路徑,訪問時直接訪問文件即可。
Ⅳ 如何將大文件寫入到資料庫中
最近利用空閑時間自己在寫一個文件備份工具,因為我磁碟上的很多文件很重要,例如很多PPT和講義。所以需要經常備份,而且因為這些文件很多,所以需要增量備份。
我嘗試用過windows自帶的ntbackup工具,但感覺不是很爽。它不支持壓縮備份,而且界面也有點宏則復雜。
為了響應偉大領袖的「自力更生,豐改衫衣足食」的號召,咱決定自己寫一個工具,專門備份到資料庫。支持壓縮,支持加密,支持增量。
本文分享一下其中一些重點的技術細節
其中一個關鍵的技術就是將文件使用二進制的方式存放在資料庫的varbinary(max)的欄位中。該欄位最大允許的長度為2GB。
對於一些小文件,我們可以一次性讀取它的所有位元組,然後一次提交到資料庫
/// <summary>
/// 這個方法演示了如何一次提交所有的位元組。這樣導致的結果是:應用程序立即需要申請等同於文件大小的內存
/// </summary>
static void SubmitFileByOnce() {
string file = @"F:\功夫熊貓.rmvb";//文件大小為519MB
byte[] buffer = File.ReadAllBytes(file);
using (SqlConnection conn = new SqlConnection("server=(local);database=demo;integrated security=true")) {
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO Files(FileName,FileContents) VALUES(@fileName,@fileContents)";
cmd.Parameters.AddRange(
new[]
{
new SqlParameter("@fileName",file),
new SqlParameter("@fileContents",buffer)
});
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
但是,上面的方法有幾個問題,主要體現在如果文件比較大的話
1. 它需要一次性很大的內存,具體數據等同於文件大小。因為File.ReadAllBytes方法是將所有位元組全部讀入到內存。
2. 它會導致提交失敗,就是因為數據太大了。資料庫也會拒絕。
那麼,我就對這個方法做了一下改進,將文件拆分為5MB一段,也就是說,此時每次申請的內存只有5MB。這就大大地提高了可用性。
/// <summary>
/// 這個方法是將文件切分為5MB的塊,每次只是提交5MB,所以可能多次提交,但內存佔用就比較小
/// </summary>
static void SubmitFileStepByStep() {
string file = @"F:\功夫熊貓.rmvb";//以這個文件為例,大小為519MB,一共需要的時間大約94秒。還是有點慢的,所以還可能需要進行壓縮
FileStream fs = new FileStream(file, FileMode.Open);
byte[] buffer = new byte[5 * 1024 * 1024];
int readCount;
using (SqlConnection conn = new SqlConnection("server=(local);database=demo;integrated security=true"核絕腔))
{
conn.Open();
while ((readCount = fs.Read(buffer, 0, buffer.Length)) > 0)
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO Files(FileName,FileContents) VALUES(@fileName,@fileContents)";
cmd.Parameters.AddRange(
new[]
{
new SqlParameter("@fileName",file),
new SqlParameter("@fileContents",buffer)
});
cmd.ExecuteNonQuery();
}
}
conn.Close();
}
}
這樣的話,有一個後果就是一個文件,可能在資料庫中會有多條記錄。所以在讀取的時候,我們需要對其進行合並
static void DownloadFile() {
string file = @"F:\功夫熊貓.rmvb";
string destfile = @"E:\Temp\Temp.wmv";
using (SqlConnection conn = new SqlConnection("server=(local);database=demo;integrated security=true"))
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT FileContents FROM Files WHERE FileName=@fileName";
cmd.Parameters.AddRange(
new[]
{
new SqlParameter("@fileName",file),
});
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
FileStream fs = new FileStream(destfile, FileMode.Append, FileAccess.Write);
while (reader.Read())
{
byte[] buffer = (byte[])reader[0];
fs.Write(buffer, 0, buffer.Length);
}
fs.Close();
reader.Close();
conn.Close();
}
}
}
本文由作者:陳希章
Ⅵ ASP讀取選擇文件夾的所有文件名寫入Access資料庫
循環讀取文件夾文件和子文件夾,可通過FSO組件完成。
FunctionBianli(path)
SetFso=server.createobject("scripting.filesystemobject")
OnErrorResumeNext
SetObjfolder=fso.getfolder(path)
SetObjsubfolders=objfolder.subfoldersNowpath=path+""+Objsubfolder.name
Response.writeNowpath
SetObjfiles=objsubfolder.files
ForEachObjfileInObjfiles
Response.write"<br>---"
Response.writeObjfile.name
Next
Response.write"<p>"
Bianli(nowpath)'遞歸
Next
SetObjfolder=nothing
SetObjsubfolders=nothing
SetFso=nothing
EndFunction
寫入資料庫
DBPath="ques.mdb"'ACCESS資料庫的文件名,請使用相對於網站根目錄的的絕對路徑
ConnStr="Provider=Microsoft.Jet.OLEDB.4.0;DataSource="&Server.MapPath(DBPath)
FunctionQuestionInMdb(byvalQuesTion)
SetConn55=server.createobject("adodb.connection")'連接組件
Conn55.openConnStr'連接資料庫
Setrs=server.createobject("adodb.recordset")
sql="selecttop1*fromqa"
rs.opensql,Conn55,1,3
rs.addnew
rs("QuesTion")=QuesTion
QuestionInMdb=rs("id")
rs.close
Setrs=Nothing
Conn55.close
SetConn55=Nothing
EndFunction
Ⅶ 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() ;
}
}
(7)讀取文件寫入資料庫擴展閱讀
樣例
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);
}
}
Ⅷ php如何讀取CSV大文件並且將其導入資料庫示例
思路:
讀取csv文件,每讀取一行數據,就插入資料庫
示例
文件夾結構
/
file.csv//csv大文件,這里只模擬三行數據,不考慮運行效率(PS:csv文件格式很簡單,文件一般較小,解析很快,運行效率的瓶頸主要在寫入資料庫操作)
index.php//php文件
file.csv
singi,20
lily,19
daming,23
index.php
/**
*讀取csv文件,每讀取一行數據,就插入資料庫
*/
//獲取資料庫實例
$dsn='mysql:dbname=test;host=127.0.0.1';
$user='root';
$password='';
try{
$db=newPDO($dsn,$user,$password);
}catch(PDOException$e){
echo'Connectionfailed:'.$e->getMessage();
}
//讀取file.csv文件
if(($handle=fopen("file.csv","r"))!==FALSE){
while(($row=fgetcsv($handle,1000,","))!==FALSE){
//寫入資料庫
$sth=$db->prepare('insertintotestsetname=:name,age=:age');
$sth->bindParam(':name',$row[0],PDO::PARAM_STR,255);
$sth->bindParam(':age',$row[1],PDO::PARAM_INT);
$sth->execute();
}
fclose($handle);
}
數據表
CREATETABLE`test`(
`id`INT(10)UNSIGNEDNOTNULLAUTO_INCREMENT,
`name`VARCHAR(255)NULLDEFAULT''COLLATE'utf8mb4_bin',
`age`INT(10)NULLDEFAULT'0',
PRIMARYKEY(`id`)
)
COLLATE='utf8mb4_bin'
ENGINE=InnoDB;
運行結束後,資料庫中會插入csv中的三行數據