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/
Related
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);
I'm creating a simple windows C# form application. but I cannot connect to local database file (.sdf)
i'm using
using System.Data.SqlServerCe;
This is my app.config file
<add name="ConnectionString1"
connectionString="Data Source=D:\Work Place_VS\Dilshan_Hardware\Dilshan_Hardware\Database\AppDB.sdf"
providerName="Microsoft.SqlServerCe.Client.3.5" />
<add name="ConnectionString2"
connectionString="Data Source=|DataDirectory|\Database\AppDB.sdf"
providerName="Microsoft.SqlServerCe.Client.3.5" />
I am trying to connect database file through following code.
try
{
using (SqlCeConnection cn = new SqlCeConnection(ConfigurationManager.ConnectionStrings["ConnectionString1"].ToString()))
{
SqlCeCommand cmd = new SqlCeCommand("SELECT routeName FROM tbl_route", cn);
cn.Open();
SqlCeDataReader reader1 = cmd.ExecuteReader();
while (reader1.Read())
{
MessageBox.Show("Result :" + reader1[0]);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error :" + ex.ToString());
}
Even I use ConnectionString1 or ConnectionString2 it always jump into catch block while try to make connectionString.
Please help me to find the error of this code.
I think you need to add a Persist Security Info value
Try the following:
<add name="ConnectionString1"
connectionString="Data Source=D:\Work Place_VS\Dilshan_Hardware\Dilshan_Hardware\Database\AppDB.sdf;Persist Security Info=false;"
providerName="Microsoft.SqlServerCe.Client.3.5"
So I have successfully add a data connection to my VS project and now I'm trying to populate the drop down menu that I created with the data from the tables coming from the database; however, when I run the code it says, "Login failed for use 'Username', on this line:
cmd.Connection.Open();
This is my C# code:
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
namespace Test1234
{
public partial class Home : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
PopulateDDList1();
//PopulateDDList2();
//PopulateDDList2_1();
}
public void PopulateDDList1()
{
SqlCommand cmd = new SqlCommand("SELECT * FROM [History]", new SqlConnection(ConfigurationManager.AppSettings["Connection"]));
cmd.Connection.Open();
SqlDataReader ddlValues;
ddlValues = cmd.ExecuteReader();
DropDownList1.DataSource = ddlValues;
DropDownList1.DataValueField = "Serial";
DropDownList1.DataTextField = "Serial";
DropDownList1.DataBind();
cmd.Connection.Close();
cmd.Connection.Dispose();
}//end Populate 1
}
}
This is the web.config code:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="ActioNetITInventoryConnectionString" connectionString="Data Source=10.10.101.188;Initial Catalog=ActioNetITInventory;User ID=rails.sa;Password=ActioNet1234"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<appSettings>
<add key="Connection" value="Data Source=10.10.101.188;Initial Catalog=ActioNetITInventory;User ID=rails.sa;Password=***********;Integrated Security=True"/>
</appSettings>
</configuration>
<appSettings>
<add key="Connection" value="Data Source=10.10.101.188;Initial Catalog=ActioNetITInventory;User ID=rails.sa;Password=***********;Integrated Security=True"/>
</appSettings>
Your connection string contains both a login & password as well as Integrated Security=True
If you are trying to log on with a named login/password, then either set Integrated Security=False or leave it out altogether
I think there error occures due to your connection string. Is there a reason that you don't use the servername but its IP?
By the way: You defined it twice in two different config sections..
If you're using the IP, then you have to add the port:
Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;
Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;
Alternatively you could use the standard way:
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
Or even better if possible: Use trusted connection:
Server=myServerAddress;Database=myDataBase;
Generally have a look here: http://www.connectionstrings.com/sql-server/
You have several potential failure points, for instance:
Calling ExecuteReader but not actually validating data, ie no Null.
Potentially several Columns being returned, when you only need a Key and Value.
Are you sure Serial is valid Column.
Your connection includes integrated security and a login / password. Use one or the other. (Kritner's answer has good information and direction for this).
To make your code a bit more legible and robust, you could do the following:
public IList<TModel> GetModel<T>(string query) where TModel : new()
{
var container = new List<T>();
using(var connection = new SqlConnection(dbConnection))
using(var command = new SqlCommand(query, connection))
{
connection.Open();
using(var reader = command.ExecuteReader())
while(reader.Read())
{
TModel model = new TModel();
var type = model.GetType();
var table = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToArray();
foreach(var property in type.GetProperties())
foreach(var column in table)
if(String.Compare(property.Name, column, true) == 0)
if(!reader.IsDBNull(reader.GetOrdinal(property.Name)))
property.SetValue(model, reader.GetValue(reader.GetOrdinal(property.Name)), null);
container.Add(model);
}
}
}
The following method will build your model, so you would simply do:
drpExample.DataSource = GetModel<Person>("SELECT * FROM [History]");
drpExample.DataBind();
You really shouldn't have a direct query like that, you should really use Parameters but this should get you started. Also you will need the DataKeyValue and DataKeyText which I often apply to the front-end. You would simply set the value to the correlated Property in your model.
As stated in my comment, you can't provide both login credentials and state integrated security=true - it's one or the other.
Integrated Security basically says "use the current domain credentials I'm logged into the system with."
That being said, you probably want it to look like this:
<add key="Connection"
value="Data Source=10.10.101.188;Initial Catalog=ActioNetITInventory;User ID=rails.sa;Password=ActioNet1234;"/>
Although the "Connection" seems redundant as you already have a connection string with the same information. You can use that like this:
SqlCommand cmd = new SqlCommand(
"SELECT * FROM [History]",
new SqlConnection(
ConfigurationManager.ConnectionStrings["ActioNetITInventoryConnectionString"].ConnectionString)
)
);
I wrote some code for getting a connection between asp.net and SQL Server but I have
Generally, the purpose of this code is to add 2 sets of data into the database using 2 text boxes.
This error is in web.config file:
Error 1 Character ';', hexadecimal value 0x3b is illegal in an XML name.
My configuration:
<?xml version="1.0"?>
<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>
In code behind :
The type or namespace name 'SqlConnection' could not be found (are you missing a using directive or an assembly reference?)
My code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication3
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["myconectionstring"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("INSERTINTO TEST (name,fathername) VALUES('" + TextBox1.Text + "','" + TextBox1.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
best regards :)
=========================================
EDIT: I had done according your suggestions and there is no more error but the data isn't added to the database, actually nothing happens when i click on submit. :(
my code:
web.config:
<?xml version="1.0"?>
<!--
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.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_Click(object sender, EventArgs e)
{
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["myconectionstring"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("INSERT INTO Table_1 (name,fathername) VALUES('" + txt1.Text + "','" + txt2.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
txt1.Text = "";
txt2.Text = "";
con.Close();
}
}
}
Error1: You have added semicolon at the end of the connection string asbelow:
connectionString="data source=.\SQLEXPRESS;initial catalogue=test;
Integrated Security=SSPI";
^^^^^
Solution1: You need to move the semicolon inside connectionstring
Try This:
connectionString="data source=.\SQLEXPRESS;initial catalogue=test;
Integrated Security=SSPI;"
Error 2: You did not import the System.Data.SqlClient namespace to use the SqlConnection class members
Solution2:
You need to import System.Data.SqlClient; Namespace asbelow
using System.Data.SqlClient;
Solution 3: initial catalogue spelling is wrong, instead you should use Initial Catalog in your Connection string asbelow:
connectionString="data source=.\SQLEXPRESS;initial catalog=test;
Integrated Security=SSPI";
EDIT: Try the following code to get the exceptiondetails
protected void Button1_Click(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 TEST (name,fathername) VALUES('" + TextBox1.Text + "','" + TextBox1.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
String ErrorMsg=ex.ToString();
}
finally
{
con.Close();
}
}
You have a couple of errors. The first is that you have placed the semi-colon (;) outside the connectionString attribute value in the configuration it should be:
<connectionStrings>
<add name="myconectionstring"
connectionString="data source=.\SQLEXPRESS;initial catalogue=test;Integrated Security=SSPI;"
providerName="System.Data.SqlClient" />
</connectionStrings>
In your code file you have not imported the required namespace try adding:
using System.Data.SqlClient
I think you should have this configuration
<connectionStrings>
<add name="myconectionstring"
connectionString="data source=.\SQLEXPRESS;initial catalog=test;Integrated Security=SSPI;"
providerName="System.Data.SqlClient" />
</connectionStrings>
or
<connectionStrings>
<add name="myconectionstring"
connectionString="server=.\SQLEXPRESS;database=test;Integrated Security=SSPI;"
providerName="System.Data.SqlClient" />
</connectionStrings>
Use Initial Catalog or database instead of your initial catalogue= (or use server= and database= which are clearer and more obvious names, in my opinion)
This website http://www.connectionstrings.com/ is a great and extensive resource about how to build valid connection strings.
And of course, as all the others have mentioned - you need to add a using System.Data.SqlClient to your code file!
Error says clearly! Remove semicolon(;) from your connection string in configuration tag.
As shown below
<connectionStrings>
<add name="myconectionstring"
connectionString="data source=.\SQLEXPRESS;initial catalogue=test;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
</connectionStrings>
Also you missed the namespace,
using System.Data.SqlClient
I can't seem to be able to access the app.config database connection string in my c# winforms app.
app.config code
<connectionStrings>
<add name="MyDBConnectionString" providerName="System.Data.SqlClient"
connectionString="Data Source=localhost;Initial Catalog=MySQLServerDB; Integrated Security=true" />
</connectionStrings>
C# code:
SqlConnection conn = new SqlConnection();
conn.ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["MyDBConnectionString"];
When I try the C# code, I get a message:
Warning 1 'System.Configuration.ConfigurationSettings.AppSettings' is obsolete: '
This method is obsolete, it has been replaced by System.Configuration!System.Configuration.ConfigurationManager.AppSettings'
However, when I try to use:
conn.ConnectionString = System.Configuration!System.Configuration.ConfigurationManager.AppSettings["MyDBConnectionString"];
I get an error: Only assignment, call, increment, decrement, and new object expressions can be used as a statement
This is all you need:
System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
Use ConfigurationManager instead of ConfigurationSettings. It has a ConnectionStrings property that you should use for connection strings in the connectionStrings section:
ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
You are using the ConnectionStrings collection, not the AppSettings.
ConfigurationManager.ConnectionStrings["MyDbConnectionString"].ConnectionString;
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ConnectionString" value="Data Source=MY-PC;Initial Catalog=DB2013;User ID=sa;Password=MYSQL123" />
</appSettings>
</configuration>
using System.Configuration;
using System.Data.SqlClient;
namespace OnlineDelete_W2013
{
public partial class CommodityEdit : Form
{
SqlConnection MyConnection = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]);
public CommodityEdit()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
MyConnection.Open();
}
catch (Exception)
{
throw;
}
}
}
}
try this
ConfigurationManager.ConnectionStrings["MyDbConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["SQLConnection"].ToString()))
{
....(your code here) ...
}
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["MyDBConnectionString"].ConnectionString;
try
{
conn.Open();
}
catch (Exception)
{
throw;
}
The answers stating to use the line
ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
are correct.
If an error appears stating that ConfigurationManager does not exist, it's because your project hasn't referenced System.Configuration.
To do that in .NET Framework, in Solution Explorer, in the project where you want to use this line of code, right-click in References, choose Add Reference..., then choose Assemblies on the left-side and Framework under it. Pick System.Configuration on the list and click Ok.
About this:
I get an error: Only assignment, call, increment, decrement, and new object expressions can be used as a statement
I just declared a var like this and solved the problem:
var strConnection = System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
Please try below code. this is as you are expecting:
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);