C# 使用SQL查询虚拟控制台在SQL Server数据库上执行任何操作

C# 使用SQL查询虚拟控制台在SQL Server数据库上执行任何操作,c#,sql-server,C#,Sql Server,如何使用富文本框和一些预连接的字符串执行直接Transact-SQL查询并将结果输入datagridview 我的GUI表单如下所示: 我想在这个富文本框中使用任何SQL查询,并在数据网格视图中获得结果 我使用这段代码来查询和填充数据gridview SqlConnection c = new SqlConnection(@"Data Source=.;Initial Catalog=db3;Integrated Security=True"); private void button1_C

如何使用富文本框和一些预连接的字符串执行直接Transact-SQL查询并将结果输入datagridview

我的GUI表单如下所示:

我想在这个富文本框中使用任何SQL查询,并在数据网格视图中获得结果

我使用这段代码来查询和填充数据gridview

SqlConnection c = new SqlConnection(@"Data Source=.;Initial Catalog=db3;Integrated Security=True");

private void button1_Click(object sender, EventArgs e)
{
        SqlDataAdapter a = new SqlDataAdapter("select * from phone", c);
        DataTable t = new DataTable();
        a.Fill(t);
        dataGridView1.DataSource = t;
}
那么我如何将其修改为这个呢

SqlConnection c = new SqlConnection(@"Data Source=.;Initial Catalog=db3;Integrated Security=True");

private void button1_Click(object sender, EventArgs e)
{
        SqlDataAdapter a = new SqlDataAdapter(Textbox1.Text, c);
        DataTable t = new DataTable();
        a.Fill(t);
        dataGridView1.DataSource = t;
}
我还在另一个按钮中使用了Pravin Deshmukh代码,并得到错误:

更新3:使用了建议的代码并得到了一个引用错误

private void button3_Click(object sender, EventArgs e)
{
            string SqlString = textBox2.Text; // here you can have your user query from textbox
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=.;Initial Catalog=db3;Integrated Security=True"].ConnectionString.ToString());
            conn.Open();

            DataSet ds = new DataSet();

            SqlCommand cmd = new SqlCommand(SqlString, conn);
            cmd.CommandType = CommandType.Text;

            SqlDataAdapter da = new SqlDataAdapter(cmd);

            da.Fill(ds);

            conn.Close();
            cmd.Dispose();
}
错误:

试试这个

string SqlString= "your sql query";
SqlConnection conn = new SqlConnection(@"Data Source=.;Initial Catalog=db3;Integrated Security=True");
conn.Open();

DataSet ds = new DataSet();

SqlCommand cmd = new SqlCommand(SqlString, conn);
cmd.CommandType = CommandType.Text;

SqlDataAdapter da = new SqlDataAdapter(cmd);


da.Fill(ds);

conn.Close();
cmd.Dispose();
设置datagridview自动生成列

编辑:

string SqlString= textbox1.Text; // here you can have your user query from textbox

这是一个非常糟糕的想法(从安全角度来看)。只给用户SQL管理工作室?否则,您可以使用普通ADO.Net执行查询,并检查结果以根据返回的
数据表确定网格布局。请记住,用户可能会键入两个查询,这将需要两个网格。SSMS比您更好地管理这一点和许多其他方面。它不是客户端,而是管理表单,我不想去sql management studio执行sql cmd,我想使用文本框或富文本框,从c#formi执行,就像您的代码bro,特别是第6行,但第一行是什么???使用什么查询??我想从textbox或rich textbox获取查询不是静态查询答案我编辑我的帖子并尝试在我的代码中使用您的代码请检查是否正确我使用了您的代码但获取错误-对象引用未设置为对象的实例。您获取的是哪一行?记住用richtextbox id替换
textbox1.Text
。textOk,我已经更新了答案中的代码以与您的sql连接相匹配,请检查