using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { /// <summary> /// 查询汽车表 /// </summary> public void Select() { //数据库连接类 SqlConnection conn = new SqlConnection("server=.;database=mydb;user=sa;pwd=123"); //创建操作对象 SqlCommand cmd = conn.CreateCommand(); //操作语句 cmd.CommandText = "select *from car"; //打开数据库连接 conn.Open(); //执行读取操作 SqlDataReader dr = cmd.ExecuteReader(); //操作dr,利用sqldatareader中的读取方法来一行行读取数据 while (dr.Read()) { Console.Write(dr[0].ToString() + " "); Console.Write(dr[1].ToString() + " "); Console.Write(dr["name"].ToString() + " "); } conn.Close(); } public void Insert(car data) { //数据库连接类 SqlConnection conn = new SqlConnection("server=.;database=mydb;user=sa;pwd=123"); //创建操作对象 SqlCommand cmd = conn.CreateCommand(); //操作语句. cmd.CommandText = "insert into car values('" + data.code + "','" + data.name + "','" + data.brand + "','" + data.time + "'," + data.oil + "," + data.powers + "," + data.exhaust + "," + data.price + ",'" + data.pic + "')"; //打开数据库连接 conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); } struct car { public int ids; public string code; public string name; public string brand; public DateTime time; public decimal oil; public int powers; public int exhaust; public decimal price; public string pic; } static void Main(string[] args) { //控制台输入数据 car data = new car(); Console.Write("请输入ids:"); data.ids = int.Parse(Console.ReadLine()); Console.Write("请输入code:"); data.code = Console.ReadLine(); Console.Write("请输入name:"); data.name = Console.ReadLine(); Console.Write("请输入brand:"); data.brand = Console.ReadLine(); Console.Write("请输入time:"); data.time = DateTime.Parse(Console.ReadLine()); Console.Write("请输入oil:"); data.oil = decimal.Parse(Console.ReadLine()); Console.Write("请输入powers:"); data.powers = int.Parse(Console.ReadLine()); Console.Write("请输入exhaust:"); data.exhaust = int.Parse(Console.ReadLine()); Console.Write("请输入price:"); data.price = decimal.Parse(Console.ReadLine()); Console.Write("请输入pic:"); data.pic = Console.ReadLine(); new Program().Insert(data); Console.ReadLine(); } } }