Syntax Error at Database Connection String asp.net & c# - c#

I have written code to connect to insert asp.net form data into an SQL server, created in Microsoft Visual Studio 2015, using c#. The issue I am having now is that I am unable to test if form works due to a Synax error. There are spaces between the text file, I am not sure if that might be the reason why there is an error? Or misplaced connection file? I copied the pathing directly from Microsoft Access. Any advice would be greatly appreciated.
Error:
Compiler Error Message: CS1003: Syntax error, ',' expected
Source Error:
Line 11: public partial class _Default : System.Web.UI.Page
Line 12: {
Line 13: SqlConnection con = new SqlConnection(#"Data
Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="C:
\Users\P\Docs\Visual Studio
2015\WebSites\WebSite2\App_Data\Database.mdf";Integrated
Security=True");
Line 14: protected void Page_Load(object sender,
EventArgs e)
Line 15: {
Source File: C:\Users\P\Docs\Visual Studio
2015\WebSites\WebSite2\Default.aspx.cs Line: 13
This is the form code in c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="C: \Users\P\Docs\Visual Studio 2015\WebSites\WebSite2\App_Data\Database.mdf";Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Unnamed1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "insert into Table values('" + pName.Text + "','" + pEmail.Text + "')";
cmd.ExecuteNonQuery();
con.Close();
}
}

You're using " two times in the same string I don't think they'll work even prepending #. Try using \" also a connection string should be in the app.config or web.config file. Never hardcoded in your source.

Should be
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=\"C: \Users\P\Docs\Visual Studio 2015\WebSites\WebSite2\App_Data\Database.mdf\";Integrated Security=True")
Because it isnt clear for the compiler what you mean. So we use "\" as a signal that the following char should be interpreted as... well a char - and not as a keyword.
Otherwise " is interpreted as start/end of a string which results in
string one: "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=\"
"unlogical" data (because not start or end sign): C: \Users\P\Docs\Visual Studio 2015\WebSites\WebSite2\App_Data\Database.mdf\
and string two: ;Integrated Security=True
Other possibility:
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=" + #"C: \Users\P\Docs\Visual Studio 2015\WebSites\WebSite2\App_Data\Database.mdf" + ";Integrated Security=True")
Anyways using a web.config/app.config is way better for your purpose.

Use connection strings and the web.config for easing changes.
web.config example:
<configuration>
<connectionStrings>
<add name="LoginDB" connectionString="Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\P\\Docs\\Visual Studio 2015\\WebSites\\WebSite2\\App_Data\\Database.mdf;Integrated Security=True" />
</connectionStrings>
</configuration>
Change your code to:
SqlConnection con = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["LoginDB"].ConnectionString);

Related

OleDB SQL Errors

Probably the worst part about using Microsoft Access and SQL is trying to connect through the OLEDB connection. The code is on the one drive and has been working without issue but this morning it has came up with this error;
"System.InvalidOperationException: 'The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.'"
Previously I was able to change the CPU from any to x86 which sometimes seemed to fix the problem but now it is not. I am running System.Data.OleDb 7.0.0 which I have not changed since starting this protect.
using System.Data.OleDb;
using System.Data;
using System;
namespace LOGIN_TAKE_FIVE
{
public partial class Form1 : Form
{
OleDbConnection connection = new OleDbConnection();
public Form1()
{
InitializeComponent();
connection.ConnectionString = (#"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:/Users/kiera/LOGIN TAKE FIVE/bin/Debug/net6.0-windows/dbNumber2.accdb");
}
private void btnAdd_Click(object sender, EventArgs e)
{
connection.Open();
OleDbCommand cmd = new OleDbCommand();
string encryptUser = EncryptString(tbUsername.Text);
string encryptPassword = EncryptString(tbPassword.Text);
string regSQL = "INSERT INTO Users ([Username], [Password]) VALUES ('" + encryptUser + "', '" + encryptPassword + "')";
cmd = new OleDbCommand(regSQL, connection);
cmd.ExecuteNonQuery();
connection.Close();
}
this code was working in full no less than 5 days ago so I am unsure what the problem is. Any help would be greatly appreciated.

asp.net cannot open database login failed

I'm using the following to retrieve data from a database but the SqlConnection won't open. It throws an error at scon.Open(). I'm sure it's elementary but I can't work it out.
protected void Page_Load(object sender, EventArgs e) {
SqlConnection scon = new SqlConnection("Data Source = .\\SQLEXPRESS; Database = populate.mdf; Integrated Security = true; Initial Catalog = populate");
StringBuilder htmlString = new StringBuilder();
if(!IsPostBack)
{
using (SqlCommand scmd = new SqlCommand())
{
scmd.Connection = scon;
scmd.CommandType = CommandType.Text;
scmd.CommandText = "SELECT * FROM populate";
scon.Open();
SqlDataReader articleReader = scmd.ExecuteReader();
htmlString.Append("'Populate page:'");
if (articleReader.HasRows)
{
while (articleReader.Read())
{
htmlString.Append(articleReader["dateTime"]);
htmlString.Append(articleReader["firstName"]);
htmlString.Append(articleReader["lastName"]);
htmlString.Append(articleReader["address"]);
htmlString.Append(articleReader["details"]);
}
populatePlaceHolder.Controls.Add(new Literal { Text = htmlString.ToString() });
articleReader.Close();
articleReader.Dispose();
}
}
}
}
I'm using this link https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx as one of my references. I'm also using SQL Server 2008 R2 Express if these information are of any help.
Here's part of the error message:
SqlException (0x80131904): Cannot open database "populate" requested
by the login. The login failed.
Any help would be greatly appreciated.
Quoted from https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx#sse, if you want to use .mdf file as a database, you should use the following connection string containing AttacheDbFileName.
<add name="ConnectionStringName"
providerName="System.Data.SqlClient"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFileName=|DataDirectory|\DatabaseFileName.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True" />
I solved it. All the connection string and other code was correct. The database just needed connecting to the Management Studio with some extra attention.

connection between asp.net , c# and sql server ( both versions are 2012)

i wrote a connection string in asp.net i.e add 2 data through 2 textboxes into the sql server database . but after pressing submit button i face to an error .
Details:
web.config:
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="myconectionstring"
connectionString="data source=.\SQLEXPRESS;initial catalogue=test;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
</configuration>
code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
namespace WebApplication3
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["myconectionstring"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
try
{
///string cs = System.Configuration.ConfigurationManager.ConnectionStrings["myconectionstring"].ConnectionString;
SqlCommand cmd = new SqlCommand("INSERT INTO Table_1 (name,fathername) VALUES('" + txt1.Text + "','" + txt2.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
String ErrorMsg = ex.ToString();
}
finally
{
con.Close();
}
}
}
}
Error message :
Server Error in '/' Application.
Keyword not supported: 'initial catalogue'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Keyword not supported: 'initial catalogue'.
Source Error:
Line 21: {
Line 22: string cs = System.Configuration.ConfigurationManager.ConnectionStrings["myconectionstring"].ConnectionString;
Line 23: SqlConnection con = new SqlConnection(cs);
Line 24:
Line 25: try
Source File: c:\Users\Admin\Documents\Visual Studio 2012\Projects\WebApplication3\WebApplication3\WebForm1.aspx.cs Line: 23
Your connection string should start as follows:
Server=myServerAddress;Database=myDataBase;
instead of your current
data source=.\SQLEXPRESS;initial catalogue=test;
This should resolve your issue.
Use:
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
And whenever you forgot a connection string of any database, go to:
http://www.connectionstrings.com
You misspelled Catalog wrong. Its
Initial Catalog
its a type at Initial Catalog correct the spelling and it should work !!
for more information :-
http://www.connectionstrings.com/sql-server-2012/

Getting sql connection string from web.config file

I am learning to write into a database from a textbox with the click of a button. I have specified the connection string to my NorthWind database in my web.config file. However I am not able to access the connection string in my code behind.
This is what I have tried.
protected void buttontb_click(object sender, EventArgs e)
{
System.Configuration.Configuration rootwebconfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Mohtisham");
System.Configuration.ConnectionStringSettings constring;
constring = rootwebconfig.ConnectionStrings.ConnectionStrings["northwindconnect"];
SqlConnection sql = new SqlConnection(constring);
sql.Open();
SqlCommand comm = new SqlCommand("Insert into categories (categoryName) values ('" + tb_database.Text + "')", sql);
comm.ExecuteNonQuery();
sql.Close();
}
I get a tooltip error for
SqlConnection sql = new SqlConnection(constring);
as
System.data.SqlClient.Sqlconnection.Sqlconnection(string) has some invalid arguments.
I want to load the connection string from the web.config in constring
You can simply give a Name to your ConnectionString in web.config file and do this:
web.config:
<add name="ConnectionStringName" connectionString=YourServer"; Initial Catalog=YourDB; Integrated Security=True"/>
Code Behind:
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringName"].ToString());
That's because the ConnectionStrings collection is a collection of ConnectionStringSettings objects, but the SqlConnection constructor expects a string parameter. So you can't just pass in constring by itself.
Try this instead.
SqlConnection sql = new SqlConnection(constring.ConnectionString);
try this
readonly SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["northwindconnect"].ToString());
I will suggests you to create a function rather than directly access the web.config file as follow
public static string GetConfigurationValue(string pstrKey)
{
var configurationValue = ConfigurationManager.AppSettings[pstrKey];
if (!string.IsNullOrWhiteSpace(configurationValue))
return configurationValue;
throw (new ApplicationException(
"Configuration Tag is missing web.config. It should contain <add key=\"" + pstrKey + "\" value=\"?\"/>"));
}
And use this function in you application

Failed to generate a user instance of SQL Server

I have a local project where I am trying to input data from an ASP:textbox to a database.
On building I get the following...
"Failed to generate a user instance of SQL Server. Only an integrated connection can generate a user instance. The connection will be closed."
I'm a little puzzled here, I have checked the database and it is active with the credentials i am trying to connect with.
Here is the code behind
C#
namespace OSQARv0._1
{
public partial class new_questionnaire : System.Web.UI.Page
{
SqlDataAdapter da = new SqlDataAdapter();
SqlConnection sqlcon = new SqlConnection(#"user id=*myuserid*;"+"password=*mypassword*;"+"Data Source=mssql.dev-works.co.uk;User Instance=True;"+"Database=devworks_osqar"+"Trusted_Connection=true;");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Create_Click(object sender, EventArgs e)
{
DataBinder ds = new DataBinder();
sqlcon.Open();
SqlCommand sqlcmd = new SqlCommand("INSERT INTO QUESTIONNAIRES (QuestionnaireName) VALUES ('"+qnrName.Text+"')");
sqlcmd.Parameters.AddWithValue("#Name", qnrName.Text);
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
}
}
}
Any help would be much appreciated.
Edited code behind (read commment below)
C#
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.Sql;
using System.Data.SqlClient;
namespace OSQARv0._1
{
public partial class new_questionnaire : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private string myConnectionString;
private SqlConnection myConn;
public new_questionnaire()
{
myConn = new SqlConnection();
myConnectionString += "Data Source=mssql.database.co.uk; Initial Catalog=devworks_osqar;User ID=myusername;Password=mypassword";
}
protected void Create_Click(object sender, EventArgs e)
{
//DataBinder ds = new DataBinder();
SqlCommand sqlcmd = new SqlCommand("INSERT INTO QUESTIONNAIRES (QuestionnaireName) VALUES ('"+qnrName.Text+"')");
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.Parameters.AddWithValue("#Name", qnrName.Text);
insert(sqlcmd);
}
private void insert(SqlCommand myCommand)
{
myConn.Open();
myCommand.ExecuteNonQuery();
myConn.Close();
}
}
}
Fix error "Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance."
Content from link pasted and altered below in case reference site is removed in the future:
Step 1.
Enabling User Instances on your SQL Server installation
First we are gonna make sure we have enabled User Instances for SQL Server installation.
Go to Query Window in SQL Server Management Studio and type this:
exec sp_configure 'user instances enabled', 1.
Go
Reconfigure
Run this query and then restart the SQL Server.
Step 2.
Deleting old files
Now we need to delete any old User Instances.
Go to your C drive and find and completely DELETE this path (and all files inside):
C:\Documents and Settings\ YOUR_USERNAME \Local Settings\Application Data\Microsoft\Microsoft SQL Server Data\SQLEXPRESS
(Dont forget to replace the bold text in the path with your current username (if you are not sure just go to C:\Documents and Settings\ path to figure it out).
After deleting this dir you can go to Visual Studio, create ASP.NET WebSite and click on your App_Data folder and choose Add New Item and then choose SQL Server Database and it should work!!!

Categories