简体   繁体   English

如何使用C#将数据插入本地数据库

[英]How to insert data into local database using C#

I am working on my first project using local database on C#.我正在使用 C# 上的本地数据库处理我的第一个项目。 I have searched on internet different code for inserting data, but nothing has worked for me.我在互联网上搜索了用于插入数据的不同代码,但没有任何效果对我有用。 I am trying different code, the problem that occurs to me is the built in functions they are using doesn't show up in my code.我正在尝试不同的代码,我遇到的问题是他们使用的内置函数没有出现在我的代码中。 Can someone share the authentic code for inserting, retrieving and deleting in local database ?有人可以分享在本地数据库中插入,检索和删除的真实代码吗?

The recent code that I have tried, some exception is occurring in SqlCeConnection .我最近尝试的代码,在SqlCeConnection发生了一些异常。

This is my code :这是我的代码:

string str="Data Source=(localdb)shop_database;Initial Catalog=shop_database;Integrated Security=True";

SqlCeConnection con = new SqlCeConnection(str);          
SqlCeDataAdapter sda = new SqlCeDataAdapter();
SqlCeCommand cmd = con.CreateCommand();

cmd.CommandText = "Insert into Account_details (Account_No,Customer_name,Customer_father_name,Profession,Mobile_No,Office_Address,House_Address,CNIC,Item_name,Item_color,Item_model,Item_engine_NO,Item_chasis_NO,Cash_price,Installment_price,Advance_given,Amount_left,Monthly_Installment,Monthly_Rent,Date_of_giving,Sponsor_name,Sponsor_father_name,Sponsor_profession,Sponsor_Address,Sponsor_CNIC,Sponsor_Mobile_No) values (@Account_No,@Customer_name,@Customer_father_name,@Profession,@Mobile_No,@Office_Address,@House_Address,@CNIC,@Item_name,@Item_color,@Item_model,@Item_engine_NO,@Item_chasis_NO,@Cash_price,@Installment_price,@Advance_given,@Amount_left,@Monthly_Installment,@Monthly_Rent,@Date_of_giving,@Sponsor_name,@Sponsor_father_name,@Sponsor_profession,@Sponsor_Address,@Sponsor_CNIC,@Sponsor_Mobile_No)";

cmd.Parameters.AddWithValue("@Account_No", this.Textbox0.Text);
cmd.Parameters.AddWithValue("@Customer_name", this.Textbox1.Text);
cmd.Parameters.AddWithValue("@Customer_father_name", this.Textbox2.Text);
cmd.Parameters.AddWithValue("@Profession", this.Textbox3.Text);
cmd.Parameters.AddWithValue("@Mobile_No", this.Textbox4.Text);
cmd.Parameters.AddWithValue("@Office_Address", this.Textbox5.Text);
cmd.Parameters.AddWithValue("@House_Address", this.Textbox6.Text);
cmd.Parameters.AddWithValue("@CNIC", this.Textbox7.Text);
cmd.Parameters.AddWithValue("@Item_name", this.Textbox14.Text);
cmd.Parameters.AddWithValue("@Item_color", this.Textbox15.Text);
cmd.Parameters.AddWithValue("@Item_model", this.Textbox16.Text);
cmd.Parameters.AddWithValue("@Item_engine_NO", this.Textbox17.Text);
cmd.Parameters.AddWithValue("@Item_chasis_NO", this.Textbox18.Text);
cmd.Parameters.AddWithValue("@Cash_price", this.Textbox19.Text);
cmd.Parameters.AddWithValue("@Installment_price", this.Textbox20.Text);
cmd.Parameters.AddWithValue("@Advance_given", this.Textbox21.Text);
cmd.Parameters.AddWithValue("@Amount_left", this.Textbox25.Text);
cmd.Parameters.AddWithValue("@Monthly_Installment", this.Textbox22.Text);
cmd.Parameters.AddWithValue("@Monthly_Rent", this.Textbox23.Text);
cmd.Parameters.AddWithValue("@Date_of_giving", this.Textbox24.Text);
cmd.Parameters.AddWithValue("@Sponsor_name", this.Textbox8.Text);
cmd.Parameters.AddWithValue("@Sponsor_father_name", this.Textbox9.Text);
cmd.Parameters.AddWithValue("@Sponsor_profession", this.Textbox10.Text);
cmd.Parameters.AddWithValue("@Sponsor_Address", this.Textbox11.Text);
cmd.Parameters.AddWithValue("@Sponsor_CNIC", this.Textbox12.Text);
cmd.Parameters.AddWithValue("@Sponsor_Mobile_No", this.Textbox13.Text);

try
{
    cmd.ExecuteNonQuery();
    MessageBox.Show("Successfully saved");
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

To edit, insert, in general interact with your database you need the class SqlCommand.要编辑、插入、通常与数据库交互,您需要 SqlCommand 类。 First you create a connection to your database with an SqlConnection object.首先,您使用 SqlConnection 对象创建到数据库的连接。 Then you pass the SQL statement as a string and the connection into the constructor of the SqlConnection class.然后将 SQL 语句作为字符串和连接传递到 SqlConnection 类的构造函数中。 Little example:小例子:

SqlConnection con = new SqlConnection("server=localhost;database=test_db;uid=root;password=yourpassword");
SqlCommand cmd = new SqlCommand("select * from your_table", con);

To retreive the data from the database you need to use the SQL Statements.要从数据库中检索数据,您需要使用 SQL 语句。 For example an SQL statement is something like:例如,一条 SQL 语句类似于:

insert into my_table (value1, value2)
values("Example", "Insertion");

When you created your SqlConnection and the SqlCommand you need to open the database connection and execute the command.当您创建 SqlConnection 和 SqlCommand 时,您需要打开数据库连接并执行命令。 Wether it's a command for receiving information from the database or editing the database you use ExecuteReader() or ExecuteNonQuery().无论它是用于从数据库接收信息还是编辑数据库的命令,您都可以使用 ExecuteReader() 或 ExecuteNonQuery()。 For example when you want to receive all the Information stored in one table you use:例如,当您想接收存储在一张表中的所有信息时,请使用:

SqlConnection con = new SqlConnection("connection string as shown above");
SqlCommand cmd = new SqlCommand("select * from example_table", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
    Console.WriteLine(reader[<table_index or attribute Name>]);

And finally dont forget to call the close method on your SqlConnection and SqlDataReader object最后不要忘记在 SqlConnection 和 SqlDataReader 对象上调用 close 方法

You are probably making two mistakes:你可能犯了两个错误:

Problem 1. Your connecting string looks like wrong.问题 1. 您的连接字符串看起来是错误的。 Instead of:代替:

Data Source=(localdb)shop_database;Initial Catalog=shop_database;Integrated Security=True";

It should be:它应该是:

Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=shop_database;Integrated Security=True";

Problem 2. You are not opening the connection before executing the command.问题2. 执行命令前没有打开连接。 Your code in the block should be like this:你在块中的代码应该是这样的:

try
{
    conn.Open(); // Open the connection
    cmd.ExecuteNonQuery();
    MessageBox.Show("Successfully saved");
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}
finally
{
    conn.Close(); // Close the connection
}

As a best practice, I recommend that you use " using " block to create your connection.作为最佳实践,我建议您使用“ using ”块来创建连接。 In that case, you don't have to explicitly close the connection and set it to null:在这种情况下,您不必显式关闭连接并将其设置为 null:

try
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        conn.Open();
        // Remaining code
    }
}
catch(Exception ex)
{
    // Manage your exception here
}

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

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