简体   繁体   English

如何使用C#.net从表中更新数据

[英]how to update data from table using C#.net

I've a form opened which is has loaded some sort of data (like username, CNIC, Contact no, etc etc) in Check boxes, now I want to update the data in such manner that I simply change the text in the text boxes and click on the save changes to save it. 我打开了一个表单,该表单已在复选框中加载了某种数据(例如用户名,CNIC,联系电话等),现在我想以仅更改文本框中的文本的方式来更新数据然后点击保存更改以保存它。 I've tried it but I am not able to do it in correct manner. 我已经尝试过,但是无法以正确的方式进行操作。

Let me show you how I've coded, the code I did in frmViewformList savechanges button is : 让我向您展示我的编码方式,在frmViewformList savechanges按钮中执行的代码是:

private void btnSaveChanges_Click(object sender, EventArgs e)
{
    string sql;
    string UserName;


    UserName = txtUserName.Text; // saving data loaded on run time to UserName 

    sql = "";
    sql += "UPDATE UserLogin";
    sql += "SET Name = "+ //how to access data I've changed in TextBox after loading +"";
    sql += "WHERE Name= " + //how to access data which was in text box right after loading + "";  //
}

I am a bit confused about how to refer to data, like the name already in the text box or the name which I have changed and how to write it in SQL query... 我对如何引用数据有些困惑,例如文本框中已有的名称或已更改的名称以及如何在SQL查询中编写数据...

This question is a bit confusing, I know. 我知道,这个问题有点令人困惑。 Let me explain; 让我解释; the form is loaded, there are text boxes which is being populated with the data in database on load event, I change the data in text boxes and save on click so that the update query runs and changes the data in database as well. 加载表单时,在加载事件中有一些填充有数据库中数据的文本框,我更改了文本框中的数据并单击保存,以便更新查询运行并更改数据库中的数据。 I'm not able to create logic here how to do this, can any one help me out, I am sorry I am a new developer of C# that's why I am a bit confused. 我无法在此处创建如何执行此操作的逻辑,任何人都可以帮助我,对不起,我是C#的新开发人员,这就是为什么我有些困惑。

You should use Sql Parameters in order to avoid SQL Injection which could leave your database vulnerable to malicious exploitation. 您应该使用Sql参数以避免SQL注入,这可能会使您的数据库容易受到恶意利用。

It's a good idea to separate the logic for performing the update to the logic where you create your query so you don't have to repeat code and so that you can maintain your code easier. 将执行更新的逻辑与创建查询的逻辑分开是一个好主意,这样就不必重复代码,从而可以更轻松地维护代码。

Here is an example you can reference: 这是您可以参考的示例:

public void DoWork()
{
    // Build Query Use @Name Parameters instead of direct values to prevent SQL Injection
    StringBuilder sql = new StringBuilder();
    sql.Append("UPDATE UserLogin");
    sql.Append("SET Name = @UpdatedName");
    sql.Append("WHERE Name = @Name");

    // Create parameters with the value you want to pass to SQL
    SqlParameter name = new SqlParameter("@Name", "whatEverOldNameWas");
    SqlParameter updatedName = new SqlParameter("@UpdatedName", txtUserName.Text);

    Update(sql.ToString(), new [] { name, updatedName });
}

private static readonly string connectionString   = "Your connection string"
private static readonly DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");

public static int Update(string sql, SqlParameter[] parameters)
{
    try
    {
        using (DbConnection connection = factory.CreateConnection())
        {
            connection.ConnectionString = connectionString;
            using (DbCommand command = factory.CreateCommand())
            {
                command.Connection  = connection;
                command.CommandText = sql;

                foreach (var parameter in parameters)
                {
                    if (parameter != null)
                        command.Parameters.Add(parameter);
                }

                connection.Open();
                return command.ExecuteNonQuery();
            }
        }
    }
    catch (Exception)
    {
        throw;
    }
}

You will want to strip all ', ", and ` characters out of your input so that people can't inject SQL. When you do SET Name = " + , you'll want to actually wrap whatever you're including in quotes because it's a string: SET Name = '" + UserName "' " +... 您将需要从输入中删除所有的','和`字符,以使人们无法注入SQL。当您执行SET Name = " + ,您实际上希望将包含在引号中的所有内容包装起来,因为它是一个字符串: SET Name = '" + UserName "' " +...

This is probably best done using 最好使用

string.Format("UPDATE UserLogin SET Name = '{0}' WHERE Name = '{1}'", UserName, FormerUserName);

Then you will execute your query by using System.Data.SqlClient; 然后,您将using System.Data.SqlClient;执行查询using System.Data.SqlClient; and then work with SqlConnection to establish a connection to the server, and execute a SqlCommand of some kind; 然后与SqlConnection一起建立与服务器的连接,并执行某种SqlCommand take a look at: http://www.codeproject.com/Articles/4416/Beginners-guide-to-accessing-SQL-Server-through-C 看一下: http : //www.codeproject.com/Articles/4416/Beginners-guide-to-accessing-SQL-Server-through-C

The following is a code snippet to insert data into database using ADO.NET and assuming SQL Server database. 下面是一个代码片段,用于使用ADO.NET并假设使用SQL Server数据库将数据插入数据库。

At the top of your .cs file you should have. 您应该在.cs文件的顶部。

using System.Data.SqlClient;  // for sql server for other data bases you should use OleClient instead.

And inside your button click event you could put the following. 在按钮单击事件中,您可以放置​​以下内容。

    // to know how to get the right connection string please check this site: http://www.connectionstrings.com
    string connString = "database connection string here";

    using (SqlConnection con = new SqlConnection(connString)) 
    {
        con.Open();
        //insert text into db
        string sql_insert = "INSERT INTO ....."; // Use parameters here.
        SqlCommand cmd_insert = new SqlCommand(sql_insert, con);
        int rowsAffected = cmd_insert.ExecuteNonQuery();    
    }

Hopefully this is enough to get you started. 希望这足以让您入门。

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

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