简体   繁体   English

如何使用Visual Studio和C#将数据插入数据库并将其保存到数据库中?

[英]How can I insert and save data into database using Visual Studio and C#?

public string ss = "Data Source=D\\SQLEXPRESS;Initial Catalog=gym;Integrated Security=True";

private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
    string q2 = "insert into gym.dbo.customer (name, weight, height, add_class, gender, fees) values ('" + this.textBox1.Text + "','" + this.textBox2.Text + "','" + this.textBox3.Text + "','" + this.comboBox1.Text + "','" + this.comboBox2.Text + "','" + this.comboBox3.Text + " ') ;";

    SqlConnection con = new SqlConnection(ss);
    SqlCommand cmd = new SqlCommand(q2, con);
    SqlDataReader read;

    try
    {
        con.Open();
        read = cmd.ExecuteReader();
        MessageBox.Show("Welcome to our gym");

        while (read.Read()) { };
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

How can I insert and save data into the database using Visual Studio and C#? 如何使用Visual Studio和C#将数据插入数据库并将其保存到数据库中?

This code throws an error. 此代码将引发错误。 Anyone please give the suggestion to me to solve the error. 有人请给我建议解决错误。

image description 图片描述

At first make sure your the data type of different column of customer table. 首先,请确保您的客户表不同列的数据类型。 Then make sure what type of data you have to save for combobox. 然后,确定必须为组合框保存的数据类型。

you have to get the selected value from your Combobox. 您必须从组合框获取选定的值。 combobox1,combobox2,combobox3 retuns only the class name combobox1,combobox2,combobox3仅调整类名称

 System.Windows.Forms.ComboBox

Besides others, it is recommended to use parameter .. like this: You can follow this example 除其他外,建议使用参数..这样:您可以按照以下示例操作

private void button1_Click(object sender, EventArgs e)
{
    using(SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\abdul samad\documents\visual studio 2013\Projects\newpro\newpro\Database1.mdf;Integrated Security=True"))
    {
        try
        {

            using (var cmd = new SqlCommand("INSERT INTO registor (Name, FullName, Password, Email, Gander) VALUES (@Name,@Fullname,@Password,@Email, @Gander)"))
            {

                cmd.Connection = con;   
                cmd.Parameters.Add("@Name", txtfname.Text);
                cmd.Parameters.Add("@Fullname", txtfname.Text);
                cmd.Parameters.Add("@Password", txtpass.Text);
                cmd.Parameters.Add("@Email", txtemail.Text);
                cmd.Parameters.Add("@Gander", comboBox1.GetItemText(comboBox1.SelectedItem));

                con.Open()
                if(cmd.ExecuteNonQuery() > 0) 
                {
                   MessageBox.Show("Record inserted"); 
                }
                else
                {
                   MessageBox.Show("Record failed");
                }
            }
        }
        catch (Exception e)
        {
            MessageBox.Show("Error during insert: " + e.Message);
        }
    }
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e) 
            { 
                SqlCommand cmd = new SqlCommand("insert into customer (name,weight,height,add_class,gender,fees) values(@name,@weight,@height,@add_class,@gender,@fees)", con); 
                cmd.Parameters.AddWithValue("name", this.textBox1.Text); 
                if (con.State == ConnectionState.Closed) 
                con.Open(); 
                cmd.ExecuteNonQuery(); 
                con.Close(); 
            }

The comments are getting a bit busy, so this is the sort of thing you need to do (including parameterising the query): 注释变得有点忙,所以这是您需要做的事情(包括参数化查询):

Specifically, you don't need a reader for an insert statement as it doesn't return a result set. 具体来说,您不需要insert语句的读取器,因为它不会返回结果集。

private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
    var sql = "insert into dbo.customer ...";
    using (var con = new SqlConnection(ss))
    {

        var cmd = new SqlCommand(sql , con);
        con.Open();
        cmd.ExecuteScalar();
        MessageBox.Show("Welcome to our gym");
    }
}

Hi check that customer table is available in gym Database. 嗨,请检查客户表在健身房数据库中是否可用。 else try this link 否则尝试此链接

I found that your connection string declaration is wrong 我发现您的连接字符串声明错误

public string ss = "Data Source=D\\SQLEXPRESS;Initial Catalog=gym;Integrated Security=True";

need to update like below 需要像下面这样更新

public string ss = "Data Source=abc\\SQLEXPRESS;Initial Catalog=gym; user id=sa; Password=123456";

Data source will be not be D, It should be Server name. 数据源将不是D,它应该是服务器名称。

enter image description here 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM