简体   繁体   English

使用VS2012建立SQL连接和创建SQL命令的正确语法是什么?

[英]What is the correct syntax for establishing an SQL connection and creating SQL Commands with VS2012?

I'm not really sure where the SqlConnection , SqlCommand and the Open() / Close() goes. 我不太确定SqlConnectionSqlCommandOpen() / Close()去向。 I want to use just the single variable cmd throughout the program, hence not using the SqlCommand cmd = new SqlCommand('SELCT * FROM blabla); 我只想在整个程序中使用单个变量cmd,因此不使用SqlCommand cmd = new SqlCommand('SELCT * FROM blabla); format. 格式。

EDIT: My code below results to the textbox having the text "System.Data.SqlClient.SqlCommand" when i click the button. 编辑:我下面的代码导致当我单击按钮时文本框具有文本“ System.Data.SqlClient.SqlCommand”。

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;
using System.Data.SqlTypes;
namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        SqlConnection con = new SqlConnection(@"Data Source=EDIOTH\SQLEXPRESS;
        Initial Catalog=Try; Integrated Security=SSPI");
        SqlCommand cmd = new SqlCommand();


        public Form1()
        {            

            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            con.Open();
            cmd.CommandText = "SELECT Pnt_Lname FROM PATIENT WHERE Pnt_ID = 1;";
            txtBox1.Text = cmd.ToString();
            con.Close();
        }
    }
}

you can create constant string to hold the connection string and then you can do as below in your button1_Click 您可以创建常量字符串来保存连接字符串,然后可以在button1_Click执行以下操作

you don't need to call the close method of sql connection when you use using block as below 当您使用using块时,您不需要调用sql连接的close方法,如下所示

using(SqlConnection con = new SqlConnection(connectionString))
using(SqlCommand cmd = con.CreateCommand())
{
   cmd.CommandText = "SELECT Pnt_Lname FROM PATIENT WHERE Pnt_ID = 1";
   con.Open();
   txtBox1.Text =cmd.ExecuteScalar() as string;
}

And also if you need to read Pnt_Lname from database you better use ExecuteScalar method 而且,如果您需要从数据库中读取Pnt_Lname ,则最好使用ExecuteScalar方法

You can use this structure. 您可以使用此结构。 Use using to properly close and dispose of SqlConnection . 使用using正确关闭和处置SqlConnection

Also, you can define the connection string in your config file and use it from there. 另外,您可以在配置文件中定义连接字符串,然后从那里使用它。

using (SqlConnection conn = new SqlConnection(@"Data Source=EDIOTH\SQLEXPRESS;
    Initial Catalog=Try; Integrated Security=SSPI"))
{
    conn.Open();

    SqlCommand command = conn.CreateCommand();
    command.CommandText = "SELECT Pnt_Lname FROM PATIENT WHERE Pnt_ID = 1";

    txtBox1.Text = (String)command.ExecuteScalar();

}

In case this would be of help to anyone, this is the answer to my question: 万一这对任何人都有帮助,这就是我的问题的答案:

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 Book
{
    public partial class frmBook : Form
    {
        SqlConnection con =
            new SqlConnection(@"Data Source=EDIOTH\SQLEXPRESS;
                Initial Catalog=XXDB; Integrated Security=SSPI");
        SqlCommand cmd;
        public frmBook()
        {
            InitializeComponent();
        }

        private void frmBook_Load(object sender, EventArgs e)
        {
            con.Open();
            cmd = new SqlCommand("SELECT min(Book_ID) FROM Book;",con);
            txtID.Text = cmd.ExecuteScalar().ToString();
            cmd = new SqlCommand("SELECT title FROM Book WHERE Book_ID = '" 
                + txtID.Text + "'", con);
            txtTitle.Text = cmd.ExecuteScalar().ToString();
            con.Close();
            btnSave.Enabled = false;
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            int count = int.Parse(txtID.Text) + 1;
            con.Open();
            cmd = new SqlCommand("SELECT title FROM Book WHERE Book_ID = '"
                + count.ToString() +"'", con);
            txtTitle.Text = cmd.ExecuteScalar().ToString();
            txtID.Text = count.ToString();
            con.Close();
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            txtID.Text = "";
            txtTitle.Text = "";
            txtAuthor.Text = "";
            btnNew.Enabled = false;
            btnSave.Enabled = true;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            con.Open();
            cmd = new SqlCommand("INSERT INTO Book (Book_ID, Title, Author) " +
                "VALUES ('"+ txtID.Text +
                "','"+ txtTitle.Text +
                "','"+ txtAuthor.Text +"');", con);
            cmd.ExecuteNonQuery();
            con.Close();
            MessageBox.Show("Data saved!");
            btnSave.Enabled = false;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

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

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