在C#中插入数据库

问题描述:

我想在C#Windows应用程序的db中插入代码,这是我的代码:

i want to insert in db in C# windows application here is my code:

string str = "Data Source=|DataDirectory|\\Database1.sdf;Persist Security Info=False;";
             Qconnection.ConnectionString = str;
            Qcommand.Connection = Qconnection;
            Qconnection.Open();
            
              string commandText = "INSERT INTO order1 VALUES('10','20','o','u')";
                Qcommand.CommandText = commandText;
                Qcommand.CommandType = CommandType.Text;
              
               // Qcommand.Parameters.AddWithValue("@RID",10 );
               // Qcommand.Parameters.AddWithValue("@amount", orderColection.list[i].amount);
              //  Qcommand.Parameters.AddWithValue("@type", orderColection.list[i].type);
              //  Qcommand.Parameters.AddWithValue("@date", orderColection.list[i].date );
                //Qcommand.ExecuteNonQuery();
                Qcommand.ExecuteReader();
         
            Qconnection.Close();


但是什么也不会发生.并且我的表为空


but nothing will happen. and my table is empty

Execute reader是错误的命令:ExecuteNonQuery是正确的.
但是,最好在插入字段时命名字段,并(按您的尝试)使用参数化查询.
看看这个模板-它应该给你的想法:
Execute reader is the wrong command: ExecuteNonQuery is correct.
However it is a very good idea to name the fields as you insert them, and (as you tried) to use parametrized queries.
Look at this template - it should give you the idea:
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand com = new SqlCommand("INSERT INTO myTable (myColumn1, myColumn2) VALUES (@C1, @C2)", con))
        {
        com.Parameters.AddWithValue("@C1", myValueForColumn1);
        com.Parameters.AddWithValue("@C2", myValueForColumn2);
        com.ExecuteNonQuery();
        }
    }

如果使用的是SDF文件,则可能应该使用SqlCEConnections和SqlCECommands而不是上面的SqlConnection和SqlCommand.

If you are using SDF files, you probably should be using SqlCEConnections, and SqlCECommands rather than the SqlConnection and SqlCommand in the above though.


首先检查与数据库的连接是否完成还是不?
然后将您的代码放入try&catch中.并解释您的问题?
First check whether connection to database is done or not?
And put your code in try & catch.And explain Your problem?


我尝试使用数据集执行最基本的功能(INSERT,EDIT,DELETE,UPDATE).

参见:

http://csharp.net-informations.com/dataset/csharp-dataset-tutorial.htm [^ ]

而这个:

http://www.dotnetperls.com/dataset [
I try to use Dataset to do the most basic functions (INSERT,EDIT,DELETE,UPDATE).

See:

http://csharp.net-informations.com/dataset/csharp-dataset-tutorial.htm[^]

And this:

http://www.dotnetperls.com/dataset[^]