C#中的SQL命令不起作用 [英] SQL command in C# doesn't work

查看:165
本文介绍了C#中的SQL命令不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将新数据添加到名为用户的数据库表中。

I am trying to add new data to the DB table called Users.

public string SendUserData(string Name, string Password, string Email)
    {
        SqlCeConnection conn = new SqlCeConnection("Data Source = " + HttpContext.Current.Server.MapPath(".") + "\\App_Data\\Database_Users.sdf");
        SqlCeCommand cmd = new SqlCeCommand("INSERT INTO User (Username, Password, Email) VALUES ('" + Name + "' , '" + Password+ "' , '" + Email + "')" , conn );

        conn.Open();

        return cmd.CommandText;
    }

它没有在表中张贴任何东西,有什么建议吗?

It doesn't post anything into the table, any suggestions?

推荐答案

命令需要执行

public string SendUserData(string Name, string Password, string Email)
{
    using(SqlCeConnection conn = new SqlCeConnection("....."))
    using(SqlCeCommand cmd = new SqlCeCommand(@"INSERT INTO User (Username, Password, Email) 
                                 VALUES (@name, @pass, @email)" , conn );
    {
        conn.Open();
        cmd.Parameters.AddWithValue("@name",  Name);
        cmd.Parameters.AddWithValue("@pass",  Password);
        cmd.Parameters.AddWithValue("@email",  EMail);
        cmd.ExecuteNonQuery();  // <- This line inserts the record in the database
    }
    // This line probably is not needed
    return cmd.CommandText;
}

任何命令至少应包含一个命令文本和打开的连接。此时,您可以调用命令提供的一种执行方法

Any command should have at least a commandtext and an open connection. At that point you could call one of the execution method provided by the command


  • ExecuteNonQuery :对于INSERT / DELETE / UPDATE或
    更改数据库架构的其他命令

  • ExecuteScalar :要从SQL语句
    中检索单个值( COUNT SUM等...)

  • ExecuteReader :获取一个DataReader,该数据读取器允许从SELECT语句中检索
    行数据

  • ExecuteNonQuery: For INSERT/DELETE/UPDATE or other commands that change the schema of the database
  • ExecuteScalar: To retrieve a single value from an SQL statement (COUNT SUM etc...)
  • ExecuteReader: To get a DataReader that allows to retrieve rows of data from a SELECT statement

在此链接有关SqlCommand用法的教程

(或任何派生的DbCommand类,例如SqlCeCommand)

At this link a tutorial about the usage of SqlCommand
(or any kind of derived DbCommand class like SqlCeCommand)

还要注意,连接并且该命令应包含在using语句中,以确保在异常情况下也不再需要它们时关闭并处置这些对象

Notice also that the connection and the command should be enclosed in a using statement to be sure to close and dispose the objects when they are no more needed also in case of exceptions

最后,请勿使用字符串串联以建立一个co mmand文字。始终使用参数化查询来避免sql注入攻击和字符串引号引起的解析问题。小数点分隔符或日期格式

Finally, do not use string concatenation to build a command text. Use always a parameterized query to avoid sql injections attacks and parsing problem with quotes in string. decimal separators or date formats

这篇关于C#中的SQL命令不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆