1 using System; 2 using System.Collections.Generic; 3 using System.Data; 4 using System.Data.SqlClient; 5 using System.Linq; 6 using System.Text; 7 using System.Threading.Tasks; 8 9 namespace ConsoleApplication3 10 { 11 class Program 12 { 13 //非静态方法 14 public SqlConnection createSqlConnection() 15 { 16 //数据库连接字符串 17 string sql = "Data Source = localhost;DataBase=db_MyDemo;User Id=sa;Password=123456"; 18 SqlConnection con = new SqlConnection(sql); 19 con.Open(); 20 return con; 21 } 22 23 //静态方法 24 public static int InsertAll() 25 { 26 //拼接sql语句 27 StringBuilder strSQL = new StringBuilder(); 28 strSQL.Append("insert into tb_SelCustomer "); 29 strSQL.Append("values("); 30 strSQL.Append("‘liuhao‘,‘0‘,‘0‘,‘13822223333‘,‘[email protected]‘,‘广东省深圳市宝安区‘,12.234556,34.222234,‘422900‘,‘备注信息‘)"); 31 Console.WriteLine("Output SQL:\n{0}", strSQL.ToString()); 32 //创建Command对象 33 SqlCommand cmd = new SqlCommand(); 34 35 //静态方法调用非静态方法 36 cmd.Connection =new Program().createSqlConnection(); 37 cmd.CommandType = CommandType.Text; 38 cmd.CommandText = strSQL.ToString(); 39 int rows = cmd.ExecuteNonQuery(); 40 return rows; 41 } 42 43 static void Main(string[] args) 44 { 45 try 46 { 47 Console.WriteLine("受影响的行数为: {0}", InsertAll()); 48 } 49 catch (Exception ex) 50 { 51 Console.WriteLine("\nError:\n{0}", ex.Message); 52 } 53 Console.Read(); 54 } 55 56 } 57 }
时间: 2024-11-06 07:18:16