How to insert record into a sql server express database table?

放肆的年华 提交于 2019-12-06 02:16:25

as people suggests, try creating the database on the server (it will be even easier to handle using Sql Management Studio). Once that's done, try the following (just tested and it works):

using (SqlConnection conn = new SqlConnection(@"Persist Security Info=False;Integrated Security=true;Initial Catalog=myTestDb;server=(local)"))
{
    SqlCommand addSite = new SqlCommand(@"INSERT INTO site_list (site_name) VALUES (@site_name)", conn);
    addSite.Parameters.AddWithValue("@site_name", "mywebsitename");
    addSite.Connection.Open();
    addSite.ExecuteNonQuery();
    addSite.Connection.Close();
}
ronak
try
{
    using (SqlConnection conn = new SqlConnection(@"Persist Security Info=False;Integrated Security=true;Initial Catalog=myTestDb;server=(local)\SQLEXPRESS;database=Inventory;Data Source=localhost\SQLEXPRESS;"))
    {
        SqlCommand addSite = new SqlCommand(@"INSERT INTO Creation (Name,Product,Quantity,Category) VALUES (@Name,@Product,@Quantity,@Category)", conn);
        addSite.Parameters.AddWithValue("@Name", textBox1.Text);
        addSite.Parameters.AddWithValue("@Product", textBox2.Text);
        addSite.Parameters.AddWithValue("@Quantity", textBox3.Text.ToString());
        addSite.Parameters.AddWithValue("@Category", textBox4.Text);
        thisConnection.Open();
        addSite.ExecuteNonQuery();
    }
}
catch
{
    thisConnection.Close();
}

try this out :

string sql = String.Format("INSERT INTO site_list (site_name) VALUES('{0}')", myTextBox.Text);
using(SqlConnection connection = new SqlConnection(myConnectionString))
{
   connection.open();
   using(SqlCommand cmd = new SqlCommand(sql, connection))
   {
      cmd.ExecuteNonQuery();
   }
}

Good luck

Herold van de Ven

Try storing your textbox value in a variable. As in:

@stringname = textbox1.text
addSite.Parameters.Add("@site_name", SqlDbType.NVarChar).Value = @stringname;

(IMPORTANT! the @ in @stringname is not necessary, but protects you against hackers!)

This code has worked wonders for me.

Herold van de Ven

My apologies. The answer I gave previously will not work because the variable name used in the insert command (in your case @site_name) must match the variables used in your sqlcommand. As in:

@site_name = textbox1.text
addSite.Parameters.Add("@site_name", SqlDbType.NVarChar).Value = textBox1.Text;

Sorry for the confusion I might have caused.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!