简体   繁体   中英

How To Get SqlConnection Instantiated?

I am following a tutorial to make an ASP.NET web app and came to the part of establishing a connection to my SQL database item I added withing VisualStudio via Add>New Item command when right-clicking on my project name in Solution Explorer.

However, after putting the appropriate namespaces, VS is not recognizing the SQLConnection I'm trying to instantiate.

I keep getting the error: "the modifier 'new' is not valid for this item" among others.

I already tried removing the "@" symbol, already tried putting the path in a string, but now VS is not even recognizing a simple string instantiation!

Here is code version 1:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace AdressBook
{
    public partial class WebForm1 : System.Web.UI.Page

        SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename|DataDirectory\AdressBookDatabase.mdf;Integrated Security=True");

Here is code version 2:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace AdressBook
{
    public partial class WebForm1 : System.Web.UI.Page

        string datapath = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename|DataDirectory\AdressBookDatabase.mdf;Integrated Security=True"

        SqlConnection conn = new SqlConnection(datapath);

I expect there to be no red/green underlines and be able to connect to my database when a button is clicked. What is wrong?

Maybe this is a copy/paste error, but you're missing the curly brace at the start of the class:

namespace AdressBook
{
    public partial class WebForm1 : System.Web.UI.Page
    {   //<---- opening curly brace required!
        string datapath = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename|DataDirectory\AdressBookDatabase.mdf;Integrated Security=True"

I have tried the following and it works for my VS2017.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection("Server=(localdb)\v11.0;Integrated Security=true;AttachDbFileName=C:\\Users\\MySelf\\Documents\\Visual Studio 2017\\Projects\\TestSQL\\TestSQL\\App_Data\\Database.mdf;");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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