簡體   English   中英

連接c#和sql server

[英]connection c# and sql server

我正在使用 C# Express 2010 和 Microsoft SQL Server 2012。

我查了很多教程,但我仍然有一個非功能程序。 這是代碼。 我究竟做錯了什么 ?

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

namespace ConnectivityWithSQL
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void addButton_Click(object sender, EventArgs e)
        {                                           
            SqlConnection con = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Data Source=WIN-710CP3ATLK2\voisardth");
            try
            {
                con.Open();
                stateLbl.Text = "Connection Reussi !";

                SqlCommand cmd = con.CreateCommand();
                cmd.CommandText = "INSERT INTO [Name], [SurName], [Age], [PetName] values('"+nameTxtBox.Text+"','"+firstNameTxtBox.Text+"','"+ageTxtBox.Text+"','"+petNametxtBox.Text+"')'";

                try
                {
                    cmd.ExecuteNonQuery();
                    stateLbl.Text = "Donnée OK";
                }
                catch(Exception)
                {
                    stateLbl.Text = "Ajout echoué";
                }

            }
            catch (Exception)
            {
                stateLbl.Text= "Connection pas Reussi !";
            }

        }
    }
}

我希望它能夠輸入 Name SurName Age 和有趣的 PetName。 然后是我沒做的部分,顯示結果

您的 SQL 查詢不正確。 您有一個插入語句,但沒有告訴 SQL Server 您希望將數據插入到哪個表中。

改變:

cmd.CommandText = "INSERT INTO [Name], [SurName], [Age], [PetName] values('"+nameTxtBox.Text+"','"+firstNameTxtBox.Text+"','"+ageTxtBox.Text+"','"+petNametxtBox.Text+"')'";

到:

cmd.CommandText = "INSERT INTO table_name ([Name], [SurName], [Age], [PetName]) values('"+nameTxtBox.Text+"','"+firstNameTxtBox.Text+"','"+ageTxtBox.Text+"','"+petNametxtBox.Text+"')'";

參考: http : //www.w3schools.com/sql/sql_insert.asp

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM