只介绍读和删
不管使用什么方法来对数据库进行操作都绕不开和数据库的连接问题,所以咱们先在App.config中添加连接字段
<connectionStrings> <add name="connString" connectionString="server=.;database=Chat;integrated security=true"/> </connectionStrings>
随后读取该字段,需要用到 System.Configuration.dll,所以在 References 中添加该dll。
涉及到对对象列表的操作的话,添加对应的实体类也是必须的
所以添加如下类示例
class UserAccount { public string Account { get; set; } public string PWD { get; set; } }
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ok,正文开始
添加一个cs文件,添加如下代码示例
挺简单的,就不解释了,在注释中都写了
using System; using System.Collections.Generic; using System.Text; using System.Configuration; using System.Data.SqlClient; namespace CMD_SQLquery { class TermsService { string connString = ConfigurationManager.ConnectionStrings["connString"].ToString(); /// <summary> /// 通过SQL对数据库进行操作 /// 核心 /// </summary> /// <param name="sql">SQL语句</param> /// <returns></returns> public int ExecuteSQL(string sql) { SqlConnection conn = new SqlConnection(connString); SqlCommand cmd = new SqlCommand(sql, conn); conn.Open(); try { int result = cmd.ExecuteNonQuery(); return result; } catch (Exception) { throw; } finally { conn.Close(); } } /// <summary> /// 拼接SQL语句 调用AddTermsVaule(string sql) /// 过程就是拼接和调用 /// </summary> /// <param name="Items">传入的需要保存的对象列表</param> public void DB_AddItems(List<UserAccount> Items) { foreach (var item in Items) { StringBuilder objStrBuilder = new StringBuilder(); objStrBuilder.Append("insert into UserAccount "); objStrBuilder.Append("(Account,PWD) "); objStrBuilder.Append("Values(‘{0}‘,‘{1}‘)"); string sql = string.Format(objStrBuilder.ToString(), item.Account, item.PWD); Console.SetCursorPosition(0, 3); Console.Write("Importing "); Console.ForegroundColor = ConsoleColor.Red; Console.Write(Items.IndexOf(item)+1); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine(" / " + Items.Count); ExecuteSQL(sql); } } } }
在主函数中调用 示例
static void Main(string[] args) { TermsService obj = new TermsService(); Console.WriteLine("Preparing Account Data ... "); List<UserAccount> items = new List<UserAccount>();//准备对象列表 for (int i = 0; i < 5; i++) { items.Add(new UserAccount { Account = "Ac--" + (i + 1).ToString(), PWD="PWD**"+ (i + 1).ToString() }); } Console.WriteLine("Prepared 5 peices of Account Data!"); obj.DB_AddItems(items);//存 Console.WriteLine("Press any key to truncate table..."); Console.ReadKey(); string sql = "truncate table UserAccount"; obj.ExecuteSQL(sql);//清空 Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
程序截图: