我将手机联系人收到列表<>并将其保存在数据库中.以下是我的代码.
这是我获取contacts-List的方法
protected override void OnCreate(Bundle bundle) {
base.OnCreate(bundle);
try {
SetContentView(Resource.Layout.Main);
TextView txtcount = this.FindViewById<TextView>(Resource.Id.textView1);
List<PersonContact> a1 = GetPhoneContacts();
Phone gp = new Phone();
gp.insertContact(a1);
} catch (System.Exception ex) {
alert(ex.Message);
}
}
Run Code Online (Sandbox Code Playgroud)
通过以下方法,我试图将联系人存储在数据库中
[WebMethod]
public string insertContact<T>(List<PersonContact> a) {
OpenConnection();
if (a.Count > 0) {
for (int i = 0; i < a.Count; i++) {
string str = "insert into phone_contact (FirstName,LastName,PhoneNumber)values('" + a[i].FirstName + "','" + a[i].LastName + "','" + a[i].PhoneNumber + "')";
SqlCommand cmd = new SqlCommand(str, con);
cmd.ExecuteNonQuery();
}
return "1";
} else {
return "1";
}
}
public class PersonContact {
public string FirstName { get; set; }
public string LastName { get; set; }
public string PhoneNumber { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
传递参数时出错
gp.insertContact(a1);
Run Code Online (Sandbox Code Playgroud)
您的方法是通用的,因为它引入了一个新的类型参数T.这就是<T>方法名称末尾的含义.
但是,您不能在任何地方使用 T - 所以只需将其设为非泛型方法:
public string InsertContact(List<PersonContact> a)
Run Code Online (Sandbox Code Playgroud)
与此同时,我强烈建议您改变数据库访问的方式:它目前容易受到SQL注入攻击.相反,您应该使用参数化SQL:每个都有一个参数FirstName,LastName和PhoneNumber.
"1"无论输入如何,你也会回来.您的方法可以更简单地编写为:
// Consider renaming to InsertContacts, as it's not just dealing with a single
// contact
public string InsertContact(List<PersonContact> contacts)
{
// You should almost certainly use a using statement here, to
// dispose of the connection afterwards
OpenConnection();
foreach (var contact in contacts)
{
// Insert the contact. Use a using statement for the SqlCommand too.
}
return "1";
}
Run Code Online (Sandbox Code Playgroud)
这假设你需要返回的值 - 如果你总是返回相同的值,为什么不把它作为一个void方法呢?