I need to connect C# with SQL Server database using app.config.
My code is:
public partial class Form1 : Form
{
string connectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
public Form1()
{
InitializeComponent();
}
public void InsertDeleteUpdate(string query)
{
try
{
SqlConnection Conn = new SqlConnection(connectionString);
Conn.Open();
SqlCommand comm = new SqlCommand(query, Conn);
comm.ExecuteNonQuery();
Conn.Close();
MessageBox.Show("Succeeded");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
and in app.config I have:
<connectionStrings>
<add name="Test1"
providerName="System.Data.SqlClient"
connectionString="Data Source=KSPR1WS126;Initial Catalog=Test1;User ID=sa" />
</connectionStrings>
but I get an error and I can't fix it:
ConfigurationErrorExeption was Unhandled Configuration system
failed to initialize
Can anyone help me please ?
Try:
var connectionString = ConfigurationManager.ConnectionStrings["Test1"].ConnectionString;
You're referencing Conn as the connection string name but referenced it as Test1 in the App.Config
Try this..
<connectionStrings>
<add name="Conn" providerName="System.Data.SqlClient"
connectionString="Data Source=KSPR1WS126;Initial Catalog=Test1;User ID=sa" />
</connectionStrings>
Try below code and then check
string connectionString = ConfigurationManager.ConnectionStrings["Test1"].ConnectionString;
Related
I have a simple Web API Application and I want to connect it to a DataBase presents in my host. This is in my web.config:
<connectionStrings>
<add name="JarasDB" connectionString="Data Source=localhost;Initial Catalog=JarasDB;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
And I'm going to test it with following codes:
public string Get(int id)
{
string connectionString = ConfigurationManager.ConnectionStrings["JarasDB"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
//
// Open the SqlConnection.
//
con.Open();
//
// The following code uses an SqlCommand based on the SqlConnection.
//
using (SqlCommand command = new SqlCommand("CREATE TABLE Customer(First_Name char(50),Last_Name char(50),Address char(50),City char(50),Country char(25),Birth_Date datetime);", con))
command.ExecuteNonQuery();
}
catch (Exception ex)
{}
}
return strings[id];
}
After publishing project in my host what happens is The Connection String will be add in ASP.NET Configuration page in Plesk panel:
After calling Get method I expect to create a table in my database but nothing happens. I want to know where is my problem.
The problem occurred because you're using SQL Server connection string to connect against MySQL database, which doesn't work as expected. Ensure that MySQL Connector .NET is referenced in your project (i.e. include MySql.Data.dll and all related assemblies), then replace your connection string from this one:
<!-- Wrong (SQL Server connection string) -->
<add name="JarasDB" connectionString="Data Source=localhost;Initial Catalog=JarasDB;Integrated Security=True;" providerName="System.Data.SqlClient" />
to this example:
<!-- Correct -->
<add name="JarasDB" connectionString="Server=localhost;Port=3306;Database=jarasdb;Uid=UserID;Pwd=XXXXX" providerName="MySql.Data.MySqlClient"/>
Additionally, it is necessary to use MySqlConnection and MySqlCommand from MySql.Data.MySqlClient namespace to execute DDL query:
// add this line on top of 'using' lines
using MySql.Data.MySqlClient;
public string Get(int id)
{
string connectionString = ConfigurationManager.ConnectionStrings["JarasDB"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(connectionString))
{
try
{
con.Open();
using (MySqlCommand command = new MySqlCommand("CREATE TABLE Customer(First_Name char(50),Last_Name char(50),Address char(50),City char(50),Country char(25),Birth_Date datetime);", con))
{
command.ExecuteNonQuery();
}
}
catch (Exception ex)
{
// throw exception here
}
}
return strings[id];
}
Reference: MySQL Connector .NET Connection Strings
I am trying to create page in asp.net page and I am getting the following error
Error:-System.NullReferenceException: Object reference not set to an instance of an object. at TestdateAssistor.user_info.Button1_Click1(Object sender, EventArgs e)
at this line
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=LAPTOP-O9SI19I0\SQLEXPRESS;Integrated Security=True"].ConnectionString);
This is my complete code
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True"].ConnectionString);
conn.Open();
String insert = "insert into Table (NAME,ADDRESS,MOBILE NO,ADHAR NO,DOB) values (#name,#add,#mob,#adhar,#dob)";
SqlCommand com = new SqlCommand(insert,conn);
com.Parameters.AddWithValue("#name",TextBox1.Text);
com.Parameters.AddWithValue("#add",TextBox2.Text);
com.Parameters.AddWithValue("#mob",TextBox3.Text);
com.Parameters.AddWithValue("#adhar", TextBox4.Text);
com.Parameters.AddWithValue("#dob", TextBox5.Text);
com.ExecuteNonQuery();
Response.Write("Successful Registration!!");
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error:-" + ex.ToString());
}
What changes should I make in the connection string?
You’re using the connection string as a key to your connection strings defined in the Web.config. So you need to define the connection string there and give it a name, then reference it in the code by name:
Web.config:
<connectionStrings>
<add name="myConnectionString" connectionString="Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True" />
</connectionStrings>
Code:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
The ConnectionStrings is a collection automatically built for you by the framework. Its content is retrieved from the web.config where you should have it defined in the proper section.
Then you retrieve its value passing the Name between the square brackets not the whole connectionstring.
string cnString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
SqlConnection conn = new SqlConnection(cnString);
and in your web.config you add the proper definition for your connectionstring
<configuration>
<connectionStrings>
<add name="MyConnection" connectionString="Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True"/>
</connectionStrings>
.....
</configuration>
Error:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True"].ConnectionString);
Solution 1:
in main program (.cs)
SqlConnection conn = new SqlConnection("Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True");
Solution 2:
in web.config
<configuration>
<connectionStrings>
<add name="MyConnection" connectionString="Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True"/>
</connectionStrings>
</configuration>
in main program (.cs)
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;);
reference: https://msdn.microsoft.com/en-us/library/d7469at0(v=vs.110).aspx
I am trying to populate a WPF DataGrid with a SQL Server table, but I am getting this exception when I try to start the App (and it enters Break Mode):
An unhandled exception of type 'System.TypeInitializationException'
occurred in PresentationFramework.dll
Additional information: The type initializer for
'System.Windows.Application' threw an exception.
MY CODE
App.config
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<connectionstrings>
<add connectionstring="Data Source=*.*.*.*; User Id=**;Password=*****; Initial Catalog=Visitas;" name="ConString"/>
</connectionstrings>
MainWindow
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Fill()
{
string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
string CmdString = string.Empty;
using (SqlConnection con = new SqlConnection(ConString))
{
CmdString = "SELECT * FROM employees_ext";
SqlCommand cmd = new SqlCommand(CmdString, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("EMPLOYEES_EXT");
sda.Fill(dt);
dataGridE.ItemsSource = dt.DefaultView;
}
}
private void button_Click(object sender, RoutedEventArgs e)
{
Fill();
}
}
Pretty simple code, but already checked everything and read tons of google info, but I am still not able to solve it :\
Since the XML is case-sensitive your connectionstring spelling is incorrect. So you should note that attribute names are case-sensitive. The s in connectionString should be Uppercase:
<connectionStrings>
<add connectionString="Data Source=*.*.*.*; User Id=**;Password=*****; Initial Catalog=Visitas;" name="ConString"/>
</connectionStrings>
i trying to run query using C#, i am getting the following problem
An OLE DB Provider was not specified in the ConnectionString. An example would be, 'Provider=SQLOLEDB;
my code
string strConString = System.Configuration.ConfigurationManager.ConnectionStrings["WorkflowConnStr"].ConnectionString.ToString();
string sqlstr = "select * from table"
OleDbConnection myConnection = new OleDbConnection(strConString);
try
{myConnection.Open();}
catch (Exception err)
{ System.Diagnostics.Debug.WriteLine(err.Message); }
OleDbCommand myCommand = new OleDbCommand(sqlstr, myConnection);
OleDbDataReader reader = myCommand.ExecuteReader();
web.config
<add name="WorkflowConnStr" connectionString="Data Source=Server;Initial Catalog=DBName;user id=usr;password=password" providerName="System.Data.OleDb.OleDbConnection"/>
any suggestion ?
Try adding this to your connection string,
Provider=SQLNCLI10.1
So it would be;
<add name="WorkflowConnStr" connectionString="Data Source=Server;Initial Catalog=DBName;user id=usr;password=password;Provider=SQLNCLI10.1" providerName="System.Data.OleDb.OleDbConnection"/>
Use SqlConnection instead of OleDbConnection.
I'm using this code to read the connection string from my app.config file but it always return a null value. My App.config file is under my project. Both methods are resulting null values:
public SqlConnection getConnection()
{
try
{
// connectionString = ConfigurationManager.AppSettings["dbConn"];
connectionString = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
connectionString = System.Configuration.ConfigurationManager.AppSettings["dbConn"];
sqlConnection = new SqlConnection(connectionString);
sqlConnection = new SqlConnection(connectionString);
}
catch (Exception ex)
{
}
return sqlConnection;
}
This is my app.config file declaration:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="dbConn" providerName="System.Data.SqlClient"
connectionString="Data Source=VANYA\SQLEXPRESS;Initial Catalog=mydatabase;User Id=sa;Password=123" />
</connectionStrings>
</configuration>
I think your problem that you try to read connection string twice, first you do it right, and second time you do it wrong, so just remove second line:
connectionString = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
sqlConnection = new SqlConnection(connectionString);
ConfigurationManager.AppSettings used to access <appSettings>...</appSettings> section of the config.
Can you please try
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="dbConn" providerName="System.Data.SqlClient"
connectionString="Data Source=VANYA\SQLEXPRESS;Initial Catalog=mydatabase;User Id=sa;Password=123" />
</connectionStrings>
<appSettings>
<add key="dbConn" value="Data Source=VANYA\SQLEXPRESS;Initial Catalog=mydatabase;User Id=sa;Password=123" />
</appSettings>
</configuration>
Then use the second method.
Make sure you select the App.Config file in the solution explorer and in the property window select Copy to Output Directory to Copy Always. Now Build the application and try again.
You simple define connection string in one class and call that string.....
public class Connection
{
/// <summary>
/// Connection String
/// </summary>
public static string ConnectionString
{
get
{
return ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
}
}
}
//Returning connction string
sqlConnection conn = new SqlConnection(Connection.ConnectionString);
connectionString=global::myProject.Properties.Settings.Default.myConnectionString