使用SqlDataReader将值插入SQL Server表

时间:2013-02-18 08:01:51

标签: 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();
userIsPresent = sqlread.HasRows;
con.Close();

但现在我需要将一些值保存到数据库中。我怎样才能做到这一点 ?我不认为我应该使用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;
}

5 个答案:

答案 0 :(得分:5)

您需要ExecuteNonQuery才能在数据库中插入记录。

s.ExecuteNonQuery();

(使用Parameterized query阻止SQL注入)

答案 1 :(得分:1)

好的,所以你要做的是插入数据库而不是从中读取,因此你必须简单地在数据库上执行sql查询而不读取从中选择的任何数据。为此,您需要使用ExecuteNonQuery语句而不是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();
}

我希望这有帮助,如果你需要别的东西可以随意问。

答案 2 :(得分:0)

在您的代码中添加:

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

答案 3 :(得分:0)

试试吧......这段代码会给出正确的信息..
name1,name2,dat是数据库

中数据表中的列名
  

public static void saveToDb()
  {
     string sqlQuery =“INSERT into NumbersTable(name1,name2,dat)values('Princee','Singhal','18/02/2012');
      SqlCommand s = new SqlCommand(sqlQuery,con);
      con.Open();
      int i = s.ExecuteNonQuery();
      如果(I> = 1)
      {
         MessageBox.Show(“Record Inserted”);
      }
      否则
      {
         MessageBox.Show(“可能会出现一些问题!”);
      }
      con.Close();
  }

答案 4 :(得分:-1)

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

 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";
    }