Im encountering a problem when setting sqlconnection.
this is my Web.Config file :
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<connectionStrings>
<add name="SimpleDB"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\FluksikartoN\Documents\SimpleDB.mdf;Integrated Security=True;Connect Timeout=30"
providerName=".NET Framework Data Provider for SQL Server"/>
</connectionStrings>
</configuration>
So basically i want to add row "Hello" to sql table named "book" which has only one string column caled "Name" on button click , but i get error : "[Win32Exception (0x80004005): The network path was not found]" and i dont see anything wrong in sqlconnection set up.
aspx.cs file :
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.Services;
namespace ProjectWWW
{
public partial class WebForm1 : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static string InsertData(string ID){
string connectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:/Users/FluksikartoN/Documents/SimpleDB.mdf;Integrated Security=True;Connect Timeout=30";
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("Insert into Book (Name) values(#Name)", con))
{
con.Open();
cmd.Parameters.AddWithValue("#Name", ID);
cmd.ExecuteNonQuery();
con.Close();
return "True";
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
InsertData("hELLO");
}
You've changed your backslashes to forward slashes. Change them back and use # to not treat them as escape characters:
string connectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\FluksikartoN\Documents\SimpleDB.mdf;Integrated Security=True;Connect Timeout=30";
or just pull it from app.config since you put it there as well:
string connectionString = ConfigurationManager.ConnectionStrings["SimpleDB"];
Why not use Web.Config connection string
string connectionString = ConfigurationManager.ConnectionStrings["SimpleDB"].ToString();
there is no need of specifying connection string on page when you have specified it in Web.Config
You can simply use like this in your .cs file
SqlConnection con = new SqlConnection(System.Configuration.CofigurationManager.ConnectionString["SqlConn"].ConnectionString.ToString());
I hope this will work for you.
Related
I am unable to connect my database from Sql-server in Visual studio for my school project. I've tried multiple solutions that didn't work... Hopefully you can help me out!
This is my ConnectionString in my App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="connString" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True" />
</connectionStrings>
</configuration>
I have written my code to be able to open a connection to my database and check if the user-credentials in the login Window are right. When clicking on btnSubmit() with the right credentials (same as in the database), it should redirect to a new Window.
Only problem is that I always receive the same error at conn.Open() when running my solution:
System.InvalidOperationException: 'The ConnectionString property has not been initialized.'
This is my code for my login Window:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using MyClassLibrary;
namespace SlnProject
{
/// <summary>
/// Interaction logic for Login.xaml
/// </summary>
public partial class Login : Window
{
public Login()
{
InitializeComponent();
}
private void btnSubmit_Click(object sender, RoutedEventArgs e)
{
string connectionString = ConfigurationManager.AppSettings["connString"];
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
String query = "SELECT COUNT(1) from [User] WHERE #login = login AND #password = paswoord";
SqlCommand sqlCmd = new SqlCommand(query, conn);
sqlCmd.CommandType = CommandType.Text;
sqlCmd.Parameters.AddWithValue("#login", txtName.Text);
sqlCmd.Parameters.AddWithValue("#password", txtPassword.Text);
int count = Convert.ToInt32(sqlCmd.ExecuteScalar());
if (count == 1)
{
Main.Content = new WpfAdmin();
}
else
{
MessageBox.Show("Foute ingave. Naam of passwoord is incorrect.");
}
}
}
private void btnKlant_Click(object sender, RoutedEventArgs e)
{
Main.Navigate(new WpfGebruiker());
}
I also verified if my connection was working and there were no problems to be seen in Visual Studio.
Does someone know how to fix this problem?
Thank you in advance.
Use the following, tested with your settings.
var connectionString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
using (var conn = new SqlConnection(connectionString))
{
conn.Open();
}
Another thing to try, see if your connection string is there in the list with Data appended to the name e.g. connStringData
var settings = ConfigurationManager
.ConnectionStrings
.OfType<ConnectionStringSettings>().ToList();
for (int index = 0; index < settings.Count(); index++)
{
Console.WriteLine($"{index,-3}{settings[index].Name,-10}{settings[index].ConnectionString}");
}
Alternate, change app.config to
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
<appSettings>
<add key="SqlServerConnection" value="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True" />
</appSettings>
</configuration>
Usage
using (var conn = new SqlConnection(ConfigurationManager.AppSettings["SqlServerConnection"]))
{
conn.Open();
Console.WriteLine("Opened");
}
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 have a grid which has a dasource selected sqlDataSource2. I have not built any query in the datasource. I have a dropdownlist with two items and I would like to select the query from the dropdownlist and after selection of the query update the grid to show the result.
This is what I have tried so far:
protected void Page_Load(object sender, EventArgs e)
{
Query1();
}
protected void Query1()
{
//if (this.IsPostBack)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["PMIcommConnectionString"].ConnectionString;
SqlDataSource2.SelectCommand = #"SELECT YEAR(custDecDate), SUM(valueXX), SUM(valueYY)
FROM bids
WHERE forBid ='"+ DropDownList3.SelectedValue +"'GROUP BY YEAR(custDecDate)'";
SqlDataSource2.DataBind();
RadGrid1.DataBind();
}
}
This is my connection string:
<add name="PMIcommConnectionString" connectionString="Data
Source=WIN-72PL3253COR\SQLEXPRESS;Initial Catalog=PMIcomm;Integrated
Security=True" providerName="System.Data.SqlClient" />
I get an error "Connection string has not been initialized" on the last line. How can I make this working? Beside the error I am getting, I am not sure if this is the correct way to do this. Sorry for asking such simple thing, I am a selflearning beginner.
The connection string is not in AppSettings.
What you're looking for is in:
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["PMIcommConnectionString"].ConnectionString;
Web.config:
<connectionStrings>
<add name="PMIcommConnectionString" connectionString="Data
Source=WIN-72PL3253COR\SQLEXPRESS;Initial Catalog=PMIcomm;Integrated
Security=True"/>
</connectionStrings>
Code Behind .cs:
using System.Configuration;
using System.Data.SqlClient;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["PMIcommConnectionString"].ConnectionString);
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;