A text file contains the following content:
4580616022644994|3000| Zhaotao
4580616022645017|6000| Yi Zhang
4580616022645090|3200| Zeng Xincha
Each of the above-mentioned documents a record of a transfer, the first column represents the account number, the second column represents the amount, the third column represents the name of the account holder.
To create a database table (MS SQL Server database, table name, and field name), insert the above file into this table one at a.
Static voidMain (string[] args) { //read the file data into the array string[] Str=file.readalllines (@"C:\Users\Administrator\Desktop\ data file. txt", Encoding.default); //iterating through an array foreach(varSinchstr) { //Split String string[] file= S.split (New Char[]{'|'}, Stringsplitoptions.removeemptyentries); //SQL statements stringsql ="INSERT into dbo.test_2 (number, moneys, name) VALUES (@number, @moneys, @name);"; //SQL ParametersSqlparameter[] Para = { NewSqlParameter ("@number", SqlDbType.NVarChar),NewSqlParameter ("@moneys", SqlDbType.Int),NewSqlParameter ("@name", SqlDbType.NVarChar),}; para[0]. Value = file[0]; para[1]. Value = Convert.ToInt32 (file[1]); para[2]. Value = file[2]; //Database Operations using(SqlConnection conn =NewSqlConnection ("Data Source=.;i Nitial catalog=test; Persist Security info=true; User Id=sa; Password=123")) { using(SqlCommand comm =NewSqlCommand (Sql,conn)) { if(para!=NULL) {Comm. Parameters.addrange (para); } if(Conn. state==connectionstate.closed) {conn. Open (); } intI=Comm. ExecuteNonQuery (); if(i>0) {Console.WriteLine ("Insert Successful"); }}}} Console.readkey (); }
View Code
. net_ adding file data to the database (interview questions)