C# 使用SqlDataReader将值插入SQL Server表

C# 使用SqlDataReader将值插入SQL Server表,c#,asp.net,sql-server,C#,Asp.net,Sql Server,这就是我如何编写select语句来检查数据库中是否有值 bool userIsPresent=false; string sqlQuery = string.Format("SELECT * FROM Person WHERE Name = '{0}'", name); SqlCommand s = new SqlCommand(sqlQuery, con); con.Open(); SqlDataReader sqlread = s.ExecuteReader(); userIsPrese

这就是我如何编写select语句来检查数据库中是否有值

bool userIsPresent=false;
string sqlQuery = string.Format("SELECT * FROM Person WHERE Name = '{0}'", name);

SqlCommand s = new SqlCommand(sqlQuery, con);
con.Open();

SqlDataReader sqlread = s.ExecuteReader();
userIsPresent = sqlread.HasRows;
con.Close();
s.ExecuteNonQuery();
但是现在我需要将一些值保存到数据库中。我该怎么做?我认为我不应该使用
SqlDataReader
,那么如何保存并确认数据是否保存到数据库中

public static bool saveToDb(string name1,string nam2, DateTime dat)
{
    bool ok=false;
    string sqlQuery = string.Format("INSERT into NumbersTable values ('{0}', '{1}','{2}')",name1,nam2,dat );

    SqlCommand s = new SqlCommand(sqlQuery, con);

    con.Open();
    SqlDataReader sr = s.ExecuteReader(); // MIGHT BE WRONG
    ok = sr.HasRows;

    con.Close();
    return ok;
}
您需要在数据库中插入记录

bool userIsPresent=false;
string sqlQuery = string.Format("SELECT * FROM Person WHERE Name = '{0}'", name);

SqlCommand s = new SqlCommand(sqlQuery, con);
con.Open();

SqlDataReader sqlread = s.ExecuteReader();
userIsPresent = sqlread.HasRows;
con.Close();
s.ExecuteNonQuery();
(用于防止SQL注入)

您需要在数据库中插入记录

bool userIsPresent=false;
string sqlQuery = string.Format("SELECT * FROM Person WHERE Name = '{0}'", name);

SqlCommand s = new SqlCommand(sqlQuery, con);
con.Open();

SqlDataReader sqlread = s.ExecuteReader();
userIsPresent = sqlread.HasRows;
con.Close();
s.ExecuteNonQuery();
(用于防止SQL注入)

在代码中添加以下内容:

con.open();
S.executeNonQuery();
在代码中添加以下内容:

con.open();
S.executeNonQuery();

只需更正现有代码中的某些内容,这肯定会对您有所帮助:

 public static bool executeMyQuery(string sqlQuery)
      {
        try
        {        con.Open();
                 SqlCommand s = new SqlCommand(sqlQuery, con);
                 s.ExecuteNonQuery();
                 con.Close();
                 return true;
         } 
       catch()
        {
          return false;
        }

    And use the above function[executeMyQuery()] anywhere you want to insert like and check whether record is inserted or not like below:

     bool isInserted = false;
     // give dummy value or get it what u want to inser on name1,nam2,dat
     string rawQuery = string.Format("INSERT into NumbersTable values ('{0}', '{1}','{2}')",name1,nam2,dat );

    isInserted = myExecuteQuery(rawQuery);

  if(isInserted)
    { 
      // lblStatus i am taking only to make you understand
      // lblStatus.text = "Record inserted succesfully";
    }
  else
    {
       // lblStatus.text = "Record insertion failed";
    }

只需更正现有代码中的某些内容,这肯定会对您有所帮助:

 public static bool executeMyQuery(string sqlQuery)
      {
        try
        {        con.Open();
                 SqlCommand s = new SqlCommand(sqlQuery, con);
                 s.ExecuteNonQuery();
                 con.Close();
                 return true;
         } 
       catch()
        {
          return false;
        }

    And use the above function[executeMyQuery()] anywhere you want to insert like and check whether record is inserted or not like below:

     bool isInserted = false;
     // give dummy value or get it what u want to inser on name1,nam2,dat
     string rawQuery = string.Format("INSERT into NumbersTable values ('{0}', '{1}','{2}')",name1,nam2,dat );

    isInserted = myExecuteQuery(rawQuery);

  if(isInserted)
    { 
      // lblStatus i am taking only to make you understand
      // lblStatus.text = "Record inserted succesfully";
    }
  else
    {
       // lblStatus.text = "Record insertion failed";
    }

好的,那么您要做的是插入到数据库中,而不是从中读取数据,因此您只需在数据库上执行sql查询,而不读取从中选择的任何数据。为此,需要使用ExecuteOnQuery语句,而不是sqlDataReader。结果会像这样

public static bool saveToDb(string name1, string nam2, DateTime dat)
{
  bool ok = false;
  string sqlQuery = "INSERT INTO NumbersTable VALUES (@name1, @nam2, @dat)";
  //This is the sql query we will use and by placing the @ symbol in front of words
  //Will establish them as variables and placeholders for information in an sql command
  //Next we create the sql command
  SqlCommand cmd = new SqlCommand(sqlQuery, con);
  //Here we will insert the correct values into the placeholders via the commands
  //parameters
  cmd.Parameters.AddWithValue("name1", name1);
  //This tells it to replace "@name1" with the value of name1
  cmd.Parameters.AddWithValue("nam2", nam2);
  cmd.Parameters.AddWithValue("dat", dat);
  //Finally we open the connection
  con.Open();
  //Lastly we tell the sql command to execute on the database, in this case inserting
  //the values
  int i = cmd.ExecuteNonQuery();
  //Here we have the results of the execution stored in an integer, this is because
  //ExecuteNonQuery returns the number of rows it has effected, in the case of this
  //Insert statement it would effect one row by creating it, therefore i is 1
  //This is useful for determining if your sql statement was successfully executed
  //As if it returns 0, nothing has happened and something has gone wrong
  con.Close();
}

我希望这对您有所帮助,如果您还需要什么,请随时询问。

好的,您希望做的是插入到数据库中,而不是从数据库中读取数据,因此您只需在数据库上执行sql查询,而不必读取从数据库中选择的任何数据。为此,需要使用ExecuteOnQuery语句,而不是sqlDataReader。结果会像这样

public static bool saveToDb(string name1, string nam2, DateTime dat)
{
  bool ok = false;
  string sqlQuery = "INSERT INTO NumbersTable VALUES (@name1, @nam2, @dat)";
  //This is the sql query we will use and by placing the @ symbol in front of words
  //Will establish them as variables and placeholders for information in an sql command
  //Next we create the sql command
  SqlCommand cmd = new SqlCommand(sqlQuery, con);
  //Here we will insert the correct values into the placeholders via the commands
  //parameters
  cmd.Parameters.AddWithValue("name1", name1);
  //This tells it to replace "@name1" with the value of name1
  cmd.Parameters.AddWithValue("nam2", nam2);
  cmd.Parameters.AddWithValue("dat", dat);
  //Finally we open the connection
  con.Open();
  //Lastly we tell the sql command to execute on the database, in this case inserting
  //the values
  int i = cmd.ExecuteNonQuery();
  //Here we have the results of the execution stored in an integer, this is because
  //ExecuteNonQuery returns the number of rows it has effected, in the case of this
  //Insert statement it would effect one row by creating it, therefore i is 1
  //This is useful for determining if your sql statement was successfully executed
  //As if it returns 0, nothing has happened and something has gone wrong
  con.Close();
}

我希望这对你有所帮助,如果你还需要什么,请尽管问。

试试看。。。此代码将给出正确的消息。
name1、name2、dat是数据库中数据表中的列名称

公共静态void saveToDb()
{
string sqlQuery=“插入NumbersTable(name1,name2,dat)值('Princee','Singhal','18/02/2012');
SqlCommand s=新的SqlCommand(sqlQuery,con);
con.Open();
int i=s.ExecuteNonQuery();
如果(i>=1)
{
MessageBox.Show(“插入的记录”);
}
否则
{
MessageBox.Show(“可能发生了一些问题!”);
}
con.Close();
}


试试看……此代码将给出正确的消息。
name1、name2、dat是数据库中数据表中的列名称

公共静态void saveToDb()
{
string sqlQuery=“插入NumbersTable(name1,name2,dat)值('Princee','Singhal','18/02/2012');
SqlCommand s=新的SqlCommand(sqlQuery,con);
con.Open();
int i=s.ExecuteNonQuery();
如果(i>=1)
{
MessageBox.Show(“插入的记录”);
}
否则
{
MessageBox.Show(“可能发生了一些问题!”);
}
con.Close();
}



你的意思是我应该保持
SqlDataReader sr=
原样,把
ExecuteReader
改成
executeronquery
?@sharonHwk,不!哈比卜,你错了。ExecuteOnQuery返回受查询影响的行数和整数。因此你不能使用SqlDataReader(因为你显然没有阅读任何东西!)@ArturUdod,是的,你是对的,我误读了OP的评论,他/她应该离开SqlDataReader,并错过了“原样”部分:)@sharonHwk,不,你不能使用SqlDataReader,你没有从数据库中阅读任何东西,您正在表中插入记录,因此不需要SqlDataReaderHanks来记录所有关于谁错了的注释。任何正确的想法都将不胜感激。您的意思是我应该保持
SqlDataReader sr=
不变,将
ExecuteReader
更改为
executeronquery
?@sharonHwk,不!哈比卜,你错了。ExecuteOnQuery返回受查询影响的行数和整数。因此你不能使用SqlDataReader(因为你显然没有阅读任何东西!)@ArturUdod,是的,你是对的,我误读了OP的评论,他/她应该离开SqlDataReader,并错过了“原样”部分:)@sharonHwk,不,你不能使用SqlDataReader,你没有从数据库中阅读任何东西,您正在表中插入记录,因此不需要SqlDataReaderHanks来记录所有关于谁错了的注释。请注意,
string.Format
不能阻止sql注入攻击。改用SQL参数!请注意,
string.Format
不会阻止sql注入攻击。改用SQL参数!这个方法会阻止SQL注入吗?我只是举个例子来说明他/她如何使用ExecuteOnQuery来检查记录是否被插入,是的,这个代码不会阻止SQL注入,我稍后会进行相应的编辑,想给出他/她卡住的地方的答案:)有人能解释为什么这个答案被否决了吗?有更好的方法吗?下面的答案也是write@coder,但为什么它被否决了?这个方法会阻止SQL注入吗?我只是举个例子来说明他/她如何使用ExecuteOnQuery检查记录是否插入,是的,这个代码不会阻止SQL注入,我以后会相应地编辑,想在他/她陷入困境的地方给出答案:)有人能解释一下为什么这个答案被否决了吗?有更好的方法吗?下面的答案也是write@coder,但是为什么被否决?这段代码有什么问题……为什么被否决?有人能告诉我原因吗?@llya lvanov这不是我的问题,是别人问的,我刚在回答中添加了executenonquery,但我的回答被否决了。好吧,公平点,我已经格式化了你的代码,并加了+1。我强烈建议您在回答中添加关于不返回状态
bool
,而是捕获低级sql异常并返回更多高级异常的注释。另外,请使用sql参数而不是
string.Format
@llya lvanov谢谢,很抱歉我没有这么做