前幾天剛拿到畢業證,昨天開始到公司報到,又開始了上班生涯啊。幾多歡喜幾多愁。從今以後,就再也不是一個學生啦,唉,好好工作吧。
今天經理要我寫個小程式把文本檔案裡面的資料導入資料庫裡面,因為資料量比較大,隻能寫程式往裡面讀啦.
因為涉及到操作SQLServer資料庫,以往沒用過,現在來試一下。給大家分享一下.
using System.Data.SqlClient;
需要引入這個命名空間.
以下是怎樣連接配接資料庫及建立表
string connString = "server=192.168.1.85;database=橋梁監測;uid=sa;pwd=123456";
SqlConnection sqlConnection = new SqlConnection(connString);
sqlConnection.Open();
string sql = "CREATE TABLE s4" +
"(GPSIndex bigint primary key,aDatetime datetime,X float,Y float,Height float,"
+ "dltaX float,dltaY float,dltaH float)";
SqlCommand cmd = new SqlCommand(sql, sqlConnection);
cmd.ExecuteNonQuery();
server 對應的是資料庫的ip位址,以後大家要連接配接SqlServer資料庫,都可以照這樣來。
FileStream aFile = new FileStream("Station_8008_Ay.txt", FileMode.Open);
StreamReader sr = new StreamReader(aFile);
strLine = sr.ReadLine();
while (strLine != null)
{
string[] str = strLine.Split(' ');
int i = 0;
// double X1 = 0, Y1 = 0;//如果資料超長就得選用double
float X1 = 0, Y1 = 0;
float Height1=0;
foreach (string strtest in str)
{
if (strtest.Trim() != "")//Trim()去除字元串頭部和尾部的空格部分
{
if (i > 1)
{
if (i == 2)
{ X1 = float.Parse(strtest); }
if (i == 3)
{ Y1 = float.Parse(strtest); }
if (i == 4)
{ Height1 = float.Parse(strtest); }
}
i++;
}
}
上面也是我今天寫的代碼,從這次動手中,學到了許多,希望多積累一下
string.Trim()函數很有用,可以去掉字元串頭部和尾部的空格部分,在與資料庫操作相關的地方,必須要求字元串很精細,一點馬虎不得,是以這個函數就很有用。
DateTime dt = System.DateTime.Now;
Int64 milliseconds = (Int64)(System.DateTime.Now - new DateTime(1970, 1, 1)).TotalMilliseconds + System.DateTime.Now.Millisecond;
string sql1 = "INSERT INTO s4(GPSIndex,aDatetime,X,Y,Height,dltaX,dltaY,dltaH)"
+ "VALUES(" + milliseconds.ToString()
+ "," + "'" + dt.ToString("yyyy-MM-dd hh:mm:ss")
+"'"
+ ","
+ X1.ToString()
+","
+Y1.ToString()
+","+Height1.ToString()
+",0,0,0)";
//MessageBox.Show(sql1);
cmd = new SqlCommand(sql1, sqlConnection);
cmd.ExecuteNonQuery();
strLine = sr.ReadLine();
Thread.Sleep(1000);
}
在插入時間的時候,千萬直接這樣-- dt.toStirng() 這樣肯定報錯,這樣資料庫無法将 字元串轉化為datetime類型
我是在我旁邊一位來公司幾年的同僚的幫助下才把這個問題解決的。
對了,另外字元類型的要加單引号,這個地方很容易出錯
csdn 不給力啊,寫個部落格麻煩死啦,代碼不知道怎麼顯示不了,坑爹得很,以後去部落格園得了.