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
Related
App.config file configuration 1
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MyDBConnectionString" connectionString="Data Source=223.29.207.133;
Initial Catalog=MBV5DBLive;User ID=smsuser;Password=sms;IntegratedSecurity=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
App.config file configuration 2
<configuration>
<connectionStrings>
<add name="MyDBConnectionString" connectionString="Data Source=localhost;
Initial Catalog=University;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
C# code
try
{
String constring = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
}
}
catch (Exception ex)
even if i debug when it comes to configuration manager code will jump to catch block and it will show "Object reference not set to an instance of an object."
What is the issue with above both configuration files?
Your connection string name seems like c_str not MyDBConnectionString.
And since you don't have any MyDBConnectionString in your web config, your ConfigurationManager.ConnectionStrings["MyDBConnectionString"] returns null and that's why you get NullReferenceException when you try to access ConnectionString property of a null reference.
If everything is okey other than that, this should work;
var constring = ConfigurationManager.ConnectionStrings["c_str"].ConnectionString;
using (var con = new SqlConnection(constring))
{
}
I wanted to make my connection string dynamic so I don't have to recompile my code for each new user.
my old connection string:
Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="C:\Users\Storm\documents\visual studio 2015\Projects\SeaSideBlissVersion2\SeaSideBlissVersion2\ShopDb.mdf";Integrated Security=True
My config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<connectionStrings>
<add name="ConnString"
connectionString="Data Source=.;Initial Catalog=ShopDB;Integrated Security=True"/>
</connectionStrings>
</configuration>
and then some code in my db class:
class DB
{
static string conn;
static SqlConnection _conn;
public DB()
{
conn = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
_conn = new SqlConnection(conn);
}
public void dbAddItem(string name, string measurement, string PLU)
{
string query = string.Format("INSERET INTO tblItems (ItemName, Measurement, Stock, PLUNumber) VALUES ({0}, {1}, {2}, {3})", name, measurement, 0, PLU);
_conn.Open();
SqlCommand comm = new SqlCommand(query, _conn);
comm.ExecuteNonQuery();
_conn.Close();
}
}
And used the following references:
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
When I call my dbAddItem method it seems to hang at _conn.Open()
I'm assuming there's something wrong with my connection string? I've looked it up and nothing that I found helped.
Seems The mistake was obvious, once I put my .mdf db into the debug folder it worked. It makes sense because there is no "exact" directory to look in.
It seems that you missed login info to the DB in the connection string.
Something like "uid=xxx;pwd=xxx".
I've got a connection string to my database in a my app.config file. I want to using the app.config file rather than copying and pasting the string in the section i want to use it is.
My app.config file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="Code_Churn_Analyiser.Properties.Settings.SVN_ConnectionString"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename="|DataDirectory|\SVN .mdf";Integrated Security=True;Connect Timeout=30;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
and my .cs file is currently like this:
private void sendToDB_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("user id=username;" +"password=password;server=serverurl;" + "Trusted_Connection=yes;" + "database=database; " + "connection timeout=30");
}
I know that this is wrong but want to use the config file instead.
Can anyone help me in how I would go about doing this.
var connectionString=ConfigurationManager.ConnectionStrings["Code_Churn_Analyiser.Properties.Settings.SVN_ConnectionString"].ConnectionString;
Note : try to keep the name of the connectionstring simpler for readability purposes.
Also,Your assembly also needs a reference to System.Configuration.dll
If you want to access the ConnectionStrings property of your application-configuration file, you have to ...
add a reference to the System.Configuration-dll.
add this to the top of the file:
using System.Configuration;
Then you can access it in this way:
string conStr = ConfigurationManager.ConnectionStrings["Code_Churn_Analyiser.Properties.Settings.SVN_ConnectionString"].ConnectionString;
using(var con = new SqlConnection(conStr))
{
// ...
}
how to add this C# code connection string in app.config file for windows forms application program ?
i see examples of adding access db but i need to add excel file data , so can't find previous question on excel file connection in app.config.
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\MISD_report.xlsx" + #";Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1;ImportMixedTypes=Text;TypeGuessRows=0""";
Try this in web config file-
<connectionStrings>
<add name="Excel07ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties='Excel 8.0'" />
<add name="ConnStrName" connectionString="Data Source=database;Initial Catalog=database-name;Persist Security Info=True;User ID=your username;Password=your password" />
</connectionStrings>
i solved this myself .
app.config settings :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MSIDConn"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\MISD_report.xlsx;Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1;ImportMixedTypes=Text;TypeGuessRows=0'"
providerName="System.Data.OleDb" />
</connectionStrings>
</configuration>
added these 2 lines in Form1.cs
using System.Data.OleDb;
using System.Configuration;
in button click event :
private void button1_Click(object sender, EventArgs e)
{
string excelconn = ConfigurationManager.ConnectionStrings["MSIDConn"].ConnectionString;
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = excelconn;
OleDbCommand command9 = new OleDbCommand
(
"SELECT P1, P2, P3 " +
" FROM [PE_Actual$] ", conn
);
DataSet ds9 = new DataSet();
OleDbDataAdapter adaptor9 = new OleDbDataAdapter(command9);
adaptor9.Fill(ds9, "testtable");
dataGridView1.DataSource = ds9.Tables[0].DefaultView;
}
Usually they sit in a section on their own:
<connectionStrings>
<add name="myConnectionName" providerName="myProvider" connectionString="Data Source=D:\MISD_report.xlsx;Extended Properties=Excel 12.0 Xml;HDR=YES;IMEX=1;ImportMixedTypes=Text;TypeGuessRows=0" />
</connectionStrings>
I do not know what the providerName for OLE/ Excel is or what name to use so the provider finds the correct connection string.
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/