简体   繁体   English

通过文本框连接到SQL DB

[英]Connect to SQL DB via Textbox

So I am trying to use a connection string that is pasted into a textbox to connect to a db when the connect button is clicked. 因此,我尝试使用单击“连接”按钮时粘贴到文本框中的连接字符串连接到数据库。 I have the following code: 我有以下代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace SQLTool
{
    public partial class SQLTool : Form
    {
        public SQLTool()
        {
            InitializeComponent();

        }
        public static SqlConnection myConnection = null;

        public void Connection()
        {
            myConnection = new SqlConnection(DBConnectionBox.Text);
            //myConnection.Open();
        }


        private void DBConnectBtn_Click(object sender, EventArgs e)
        {
            SqlConnection myConnection = new SqlConnection(DBConnectionBox.Text.ToString());
            myConnection.ConnectionString = "Data Source=ServerName;" + "Initial Catalog=DatabaseName;" + "User ID=UserName;" + "Password=Password";
            myConnection.Open();

            if (myConnection !=null && myConnection.State == ConnectionState.Closed)
            {
                MessageBox.Show("SUCCESS!!");
            }


        }




    }
}

I have added a picture of my form. 我已经添加了一张表格的图片。 The combobox I will be adding data from the db I connect to. 我将从我连接的数据库中添加数据的组合框。 So any help on that would be appreciated as well. 因此,对此的任何帮助也将不胜感激。 Form Picture 表格图片

Maybe someone can point me into the right direction. 也许有人可以指出我正确的方向。 The if statement was just for testing if I was connecting to the db. if语句仅用于测试是否连接到数据库。 This is my first time trying something like this so I am a bit lost. 这是我第一次尝试这样的事情,所以我有点迷路。 Any help would be greatly appreciated. 任何帮助将不胜感激。

UPDATE: 更新:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace SQLTool
{
    public partial class SQLTool : Form
    {
        public SQLTool()
        {
            InitializeComponent();

        }
        public static SqlConnection myConnection = null;




        private void DBConnectBtn_Click(object sender, EventArgs e)
        {

            try
            {
                var myConnection = new SqlConnection(DBConnectionBox.Text);
                myConnection.Open();
                if (myConnection.State == ConnectionState.Open)
                {
                    var sqlCmd = new SqlCommand("SELECT * FROM Menu", myConnection);
                    var sqlReader = sqlCmd.ExecuteReader();

                    while (sqlReader.Read())
                        ClientComboBox.Items.Add(sqlReader["Name"].ToString());

                    //MessageBox.Show("SUCCESS!!");


                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Failed to connect. Message {ex.Message}");
            }


        }


    }
}

The only thing left to do is to populate the datagridview with a SQL Query that is ran depending on what I pick in the combobox. 剩下要做的唯一一件事就是用一个SQL查询填充datagridview,该查询取决于我在组合框中选择的内容。

Ok guys, new problem: 好的,新问题:

private void ClientComboBox_SelectedIndexChanged(object sender, EventArgs e)
    {

        try
        {
            var myConnection = new SqlConnection(DBConnectionBox.Text);
            myConnection.Open();
            if  (myConnection.State == ConnectionState.Open)
            {
                var Cmd = new SqlCommand("SELECT * FROM Menu WHERE Name ='" + ClientComboBox.Text + "';");
                var Reader = Cmd.ExecuteReader();

                while(Reader.Read())
                {
                    SqlDataAdapter sqlDataAdap = new SqlDataAdapter(Cmd);

                    DataSet dtRecord = new DataSet();
                    sqlDataAdap.Fill(dtRecord);
                    ClientInfoDGV.DataSource = dtRecord;

                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

When I click on a combobox item something is populated in the datagridview (ClientInfoDGV). 当我单击组合框项目时,datagridview(ClientInfoDGV)中将填充一些内容。 It goes straight to the catch. 它直接抓住了。

You should not reinitialize ConnectionString property of myConnection object, since it is already initialized. 您不应该重新初始化myConnection对象的ConnectionString属性,因为它已经被初始化。

Also notice that you should check for myConnection.State == ConnectionState.Open in order to determine where connection is opened or not. 还要注意,您应该检查myConnection.State == ConnectionState.Open以确定是否在哪里打开连接。

You can try following 您可以尝试关注

public static SqlConnection myConnection = null;
private void DBConnectBtn_Click(object sender, EventArgs e)
{
  try
  {
    var myConnection = new SqlConnection(DBConnectionBox.Text);
    myConnection.Open();
    if (myConnection.State == ConnectionState.Open)
      MessageBox.Show("SUCCESS!!");
  }
  catch (Exception ex)
  { MessageBox.Show($"Failed to connect. Message {ex.Message}"); }
}

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

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