简体   繁体   English

SQL C#,命令(查询)执行两次

[英]SQL C#, command(query) is executing twice

I have simple app to build sql query (for educational purposes). 我有一个简单的应用程序来构建sql查询(出于教育目的)。 I created textarea where user can write his command to sql, then program has to execute it or catch Sqlexeption. 我创建了textarea,用户可以在其中将命令写入sql,然后程序必须执行它或捕获Sqlexeption。 I know about safety etc. but its ok- user can delete everything :) 我知道安全性等知识,但是可以的用户可以删除所有内容:)

ok. 好。 here is the code: 这是代码:

query = text from textarea(its SQL command) 查询=来自textarea的文本(其SQL命令)

if (!String.IsNullOrEmpty(query) || !String.IsNullOrWhiteSpace(query))
{
    string conString = ConfigurationManager.ConnectionStrings["StudentDataBase"].ConnectionString;

    try
    { 
        using (SqlConnection SqlCon = new SqlConnection(conString))
        {                
            try
            {
                SqlCommand command = new SqlCommand(query, SqlCon);
                SqlCon.Open();

                command.ExecuteScalar();

                int numOfRows = 0;

                SqlDataAdapter adpt = new SqlDataAdapter(command);
                DataTable dt = new DataTable();
                DataSet dset = new DataSet();
                adpt.Fill(dset);
                dt = dset.Tables[0];
                if (dt.Rows.Count > 0)
                {
                    numOfRows = dt.Rows.Count;
                    gridview_results.DataSource = dt;
                    gridview_results.DataBind();

                    Sql_error = "Done. Results: " + numOfRows + " rows.";
                    container_sql_error.Style.Add("background-color", "#b9ffcb");
                }
                else
                {
                    Sql_error = "0 rows to show.";
                }                           

                SqlCon.Close();
            }
             catch (SqlException ex)
            {
               Sql_error = "Error: " + ex.Message;
               container_sql_error.Style.Add("background-color", "#ff9600");
            }
        }
    }
    catch (SqlException ex)
    {
        Sql_error = "Error... " + ex.Message;
        container_sql_error.Style.Add("background-color", "#ff9600");
    }
}

And now, when im trying: 现在,当我尝试时:

SELECT * FROM test its OK. SELECT * FROM test其确定。 GridView showing data. GridView显示数据。

slleeeccct * from testsste its OK - showing an error. slleeeccct * from testsste它的确定-显示错误。

INSERT INTO test (col1) VALUES ('aaa') its NOT OK- program throws error System.IndexOutOfRangeException: cannot find table 0 BUT command was excecuted properly BUT TWICE. INSERT INTO test (col1) VALUES ('aaa')的NOT OK-程序抛出错误System.IndexOutOfRangeException: cannot find table 0 BUT命令被正确执行了两次。

Now i have a questions: why command is excecuting TWICE(2x same data in DB) and why is there an Error about finding table 0 (is it about GridView maybe- cant fill GV with insert into )? 现在我有一个问题:为什么命令执行TWICE(数据库中2x相同的数据),为什么finding table 0出错(关于GridView可能无法用insert into填充GV)?

First of all, you are executing the code twice 首先,您要执行两次代码

-> one time you are using ExecuteScalar and the other you are using the SQLAdapter to fill the dataset with returned results, you can just use it like the below: ->一次使用ExecuteScalar,另一次使用SQLAdapter用返回的结果填充数据集,则可以像下面这样使用它:

1- dataset ds=new dataset();

2- adapter.fill(ds);

3- return ds; 

and that's it :) 就是这样:)

Regarding the insert query error, that's normal as well because the insert statement using Execute Scalar will Executes the query, and returns the first column of the first row in the result set returned by the query. 关于插入查询错误,这也是正常的,因为使用Execute Scalar的insert语句将执行查询,并返回查询返回的结果集中第一行的第一列。 Additional columns or rows are ignored. 其他列或行将被忽略。

so when you use Insert statement, you are having an error because either 因此,当您使用Insert语句时,您会遇到错误,因为

1- the command wasn't executed successfully and returned an error "Check if databsae has the inserted row you just typed" 1-命令未成功执行,并返回错误“检查databsae是否具有您刚刚键入的插入行”

2- dataset tables has no data, you can make an IF Statement check before you try to read from it like 2-数据集表中没有数据,您可以在尝试从中读取之前先进行IF语句检查

"If(ds.tables.count>0) {do something}"

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

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