如何使用C#将数据从Windows Mobile 5.0 Pocket PC插入SQLce

问题描述:


我是使用C#的Windows Mobile应用程序的新手. 在我的应用程序中,我可以从数据库SQLce中读取数据.
但不能插入........
我的代码如下:-

Hi ,
i am new in windows mobile application using C#.
in my application i can read data from database SQLce.
but can''t insert........
my code are bellow:-

try
   {
    using (SqlCeConnection con = new SqlCeConnection(DBConn.connString))
     {
      con.Open();
      string SQL = "INSERT INTO USERINFO(UserID,Password,Name,Cell,Email,Status) VALUES ('"+txtUserID.Text+"','"+txtPassword.Text+"','"+txtName.Text+"','"+txtCellNo.Text+"','"+txtEmail.Text+"',0)";
     SqlCeCommand com = new SqlCeCommand(SQL, con);
     com.ExecuteNonQuery();
     MessageBox.Show("User Registration Successfull!");
     }
    }
   catch {
     MessageBox.Show("Registration Failed!");
   }


代码已执行.....
但是没有插入数据...
详细信息:----------
VS 2008
3.5 .NET Framework
SQL CE
Windows XP SP2
Windows Mobile应用程序5.0 Pocket PC

请帮助我.....


the code is execute.....
but data not inserted...
Details:----------
VS 2008
3.5 .NET framework
SQL CE
Windows XP SP2
Windows Mobile Application 5.0 Pocket PC

please help me.....

事物的结合:
您怎么知道它不起作用?您是否收到注册失败!"信息框?还是它不出现在您的数据库中?

这里需要进行一些更改:
1)不要这样做.您很容易遭受SQL注入攻击,甚至是错误的攻击.而是使用SqlCeCommand.AddWithValue:
Couple of things:
How do you know it did not work? Do you get the "Registration Failed!" message box? Or does it not appear in your database?

Several changes are needed here:
1) Don''t do it this way. You are wide open to an SQL Injection attack, even by mistake. Instead, use SqlCeCommand.AddWithValue:
using (SqlCeConnection con = new SqlCeConnection(DBConn.connString))
  {
  con.Open();
  string SQL = "INSERT INTO USERINFO (UserID,Password,Name,Cell,Email,Status)" +
               " VALUES (@ID, @PW, @NM, @CN, @EM, 0)";
  SqlCeCommand com = new SqlCeCommand(SQL, con);
  com.AddWithValue("@ID", txtUserID.Text);
  com.AddWithValue("@PW", txtPassword.Text);
  com.AddWithValue("@NM", txtName.Text);
  com.AddWithValue("@CN", txtCellNo.Text);
  com.AddWithValue("@EM", txtEmail.Text);
  com.ExecuteNonQuery();
  MessageBox.Show("User Registration Successfull!");
  }


2)更改您的异常,使其能够捕获并报告问题:


2) Change your exception so that it catches and reports the problem:

catch (Exception ex)
   {
   MessageBox.Show("Registration Failed!\n" + ex.ToString());
   }

这样,至少可以告诉您您有问题,并为您提供有关问题所在的信息! (使用空的catch块被认为是不好的做法)

第二个更改可能为您提供了足够的信息来解决该问题:可能是UserID已经存在,或类似的问题.

That way at least it tells you you have a problem and give you information on what the problem is! (It is considered bad practice to use empty catch blocks)

The second change may give you enough info to solve the problem: It may be that the UserID already exists, or a similar problem.