public insert() {
Console.Write("请输入姓名:");
String name = Console.ReadLine();
Console.Write("请输入年龄:");
String age = Console.ReadLine();
Console.Write("请输入地址:");
String add = Console.ReadLine();
SqlConnection conn = new SqlConnection(@"server=.;database=mydb;uid=sa;pwd=sa");
//第一种占位符的使用方式
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "insert into login values(@username,@userage,@useradd)";
cmd.Parameters.AddWithValue("@username", name);
cmd.Parameters.AddWithValue("@userage", age);
cmd.Parameters.AddWithValue("@useradd", add);
//第二种占位符的使用方式
String sql = string.Format("insert into login values('{0}',{1},'{2}')", name, age, add);
SqlCommand cmd = new SqlCommand(sql, conn);
try {
conn.Open();
int i = cmd.ExecuteNonQuery();
if (i > 0) {
Console.WriteLine("插入数据成功");
}
cmd.Dispose();
conn.Close();
} finally {
conn.Close();
}
}
分享名称:C#连接数据库部分占位符的使用实例
文章路径:
http://cdweb.net/article/gchjdd.html