连接无法在visual studio中使用localdb

时间:2015-04-21 00:53:51

标签: c# visual-studio-2013 connection-string

很抱歉要问这个我知道还有很多其他问题,并尝试使用提供的解决方案,但我无法让我的代码工作。谢谢你的期待!

连接字符串,如属性:

中所示
  

数据   源=(的LocalDB)\ V11.0; AttachDbFilename =" C:\用户\雅各布\文档\ Visual   工作室   2013 \项目\ WindowsFormsApplication2 \ WindowsFormsApplication2 \ ChatDB.mdf&#34 ;;集成   安全=真

app.config中的连接字符串:

  

数据   源=(的LocalDB)\ V11.0; AttachDbFilename = | DataDirectory目录| \ ChatDB.mdf;集成   安全=真

Error: An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near the keyword 'User'.

代码:

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;
//NC-1 More namespaces.
using System.Data.SqlClient;
using System.Configuration;

namespace WindowsFormsApplication2
{
    public partial class SignUp : Form
    {
        string connstr = ConfigurationManager.ConnectionStrings["WindowsFormsApplication2.Properties.Settings.ChatDBConnectionString"].ToString();

        public SignUp()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void SubmitBtn_Click(object sender, EventArgs e)
        {
            string Name = NameText.Text;
            string Pwd = PwdText.Text;
            //make sure they have entered text
            if (Name.Length > 0 && Pwd.Length > 0)
            {
               SqlConnection conn = new SqlConnection(connstr);

                //NC-10 try-catch-finally
                try
                {
                    //NC-11 Open the connection.
                    conn.Open();

                    SqlCommand insert = new SqlCommand();
                    insert.Connection = conn;
                    insert.CommandText = "INSERT INTO [User] (Name,Password) VALUES ('" + Name + "','" + Pwd + "')";

                    insert.ExecuteNonQuery();
                    MessageBox.Show("Congrats!!!");

                }
                catch
                {
                    //NC-14 A simple catch.

                    MessageBox.Show("User was not returned. Account could not be created.");
                }
                finally
                {
                    //NC-15 Close the connection.
                    conn.Close();
                }
            }
            //if no text make them enter
            else
            {
                MessageBox.Show("Please enter Text in both fields.");
            }
        }
    }
}

再次感谢您的期待。

1 个答案:

答案 0 :(得分:1)

问题在于您的SQL查询,因为您使用的是Reserved Keywords

尝试将您的表名更改为tblUser

我还建议使用参数化查询来防止将来的SQL注入:(例如)

@"INSERT INTO [User] (Name,Password) VALUES (@Name, @Password);"