Unable to open database connection from configuration value - c#

Firstly I am aware that this has been asked many times, but I could not find anything related to my problem specifically. basically I have text inputs I need to insert into a local DB, I've checked my connection string many times, and pretty certain it isn't the problem.
<add name="ElectricsOnline"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\electricsonline.mdf;Integrated Security=True"
providerName="System.Data.SqlClient"/>
and here is the method for inserting
protected void btnSubmit_Click(object sender, EventArgs e)
{
using (var connection = new SqlConnection("ElectricsOnline"))
{
connection.Open();
var sqlStatement = "INSERT INTO Orders (FirstName, LastName, Phone, Address, Suburb, State, Postcode, Ctype, CardNo, ExpDate, Email) VALUES(#FirstName, #LastName, #Phone, #Address, #Suburb, #State, #Postcode, #Ctype, #CardNo, #ExpDate, #Email)";
using (var cmd = new SqlCommand(sqlStatement, connection))
{
cmd.Parameters.AddWithValue("#FirstName", txtFirstname.Text);
cmd.Parameters.AddWithValue("#LastName", txtLastname.Text);
cmd.Parameters.AddWithValue("#Phone", txtPhone.Text);
cmd.Parameters.AddWithValue("#Address", txtAddress.Text);
cmd.Parameters.AddWithValue("#Suburb", txtSuburb.Text);
cmd.Parameters.AddWithValue("#State", txtState.Text);
cmd.Parameters.AddWithValue("#Postcode", txtPostcode.Text);
cmd.Parameters.AddWithValue("#Ctype", ddlCtype.SelectedValue.ToString());
cmd.Parameters.AddWithValue("#CardNo", txtCardno.Text);
cmd.Parameters.AddWithValue("#ExpDate", txtExpDate.Text);
cmd.Parameters.AddWithValue("#Email", txtEmail.Text);
cmd.ExecuteNonQuery();
}
}
Response.Redirect("CheckoutReview.aspx");
}
Source error shows this
Format of the initialization string does not conform to specification starting at index 0.
Line 22: {
Line 23:
Line 24: using (var connection = new SqlConnection("ElectricsOnline"))
Line 25: {
Line 26: connection.Open();
Any help would be greatly appreciated!

You cannot use the name of your connection from configuration file directly, because new SqlConnection(...) needs a connection string itself, not its name from the config file.
You need to retrieve connection string from config before using it to create connections. Change your code as follows:
var connStr = System
.Configuration
.ConfigurationManager
.ConnectionStrings["ElectricsOnline"]
.ConnectionString;
using (var connection = new SqlConnection(connStr)) {
...
}

new SqlConnection("ElectricsOnline")
I don't know where you got the idea that you could pass in the name of a configuration value. You need to pass in the connection string. Read it from your configuration and pass it to the constructor.

Related

C# MS Access Database Connection System.Data.SqlClient.SqlException' occurred in System.Data.dll

I am not sure if this problem has anything to do with my code or simply the way that my database is set up. Any pointers would be awesome!
This is the error message that I get:
I have gone to "Modify Connection" and used the 'Test Connection' tool and that says that it connects fine but when the actual program runs nothing happens and I get the error.
Here is my code:
private void btnAddCustomer_Click(object sender, EventArgs e)
{
SqlConnection CustomerInfo = new SqlConnection("Data Source=C:\\Users\\Cory\\Desktop\\DeluxWrapsWindows\\DeluxWrapsWindows\\DeluxWraps_DB.mdb");
{
SqlCommand xp = new SqlCommand("Insert into CustomerInfo(LastName, FirstName, Email, PhoneNumber, Address, Instagram, CarMake, CarModel, AdditionalNotes) Values(#LastName, #Firstname, #Email, #PhoneNumber, #Address, #Instagram, #CarMake, #CarModel, #AdditionalNotes)", CustomerInfo);
xp.Parameters.AddWithValue("#LastName", txtLastName.Text);
xp.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
xp.Parameters.AddWithValue("#Email", txtEmail.Text);
xp.Parameters.AddWithValue("#PhoneNumber", txtPhoneNumber.Text);
xp.Parameters.AddWithValue("#Address", txtAddress.Text);
xp.Parameters.AddWithValue("#Instagram", txtInstagram.Text);
xp.Parameters.AddWithValue("#Carmake", txtCarMake.Text);
xp.Parameters.AddWithValue("#CarModel", txtCarModel.Text);
xp.Parameters.AddWithValue("#AdditionalNotes", txtAdditionalNotes.Text);
CustomerInfo.Open();
xp.ExecuteNonQuery();
CustomerInfo.Close();
}
}
You should try create the SqlCommand with:
SqlCommand xp = CustomerInfo.CreateCommand();
See this example:
https://msdn.microsoft.com/pt-br/library/system.data.sqlclient.sqlconnection.createcommand(v=vs.110).aspx
Update:
Try use OleDbConnection. See:
public DataSet GetDataSetFromAdapter(
DataSet dataSet, string connectionString, string queryString)
{
using (OleDbConnection connection =
new OleDbConnection(connectionString))
{
OleDbDataAdapter adapter =
new OleDbDataAdapter(queryString, connection);
// Set the parameters.
adapter.SelectCommand.Parameters.Add(
"#CategoryName", OleDbType.VarChar, 80).Value = "toasters";
adapter.SelectCommand.Parameters.Add(
"#SerialNum", OleDbType.Integer).Value = 239;
// Open the connection and fill the DataSet.
try
{
connection.Open();
adapter.Fill(dataSet);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// The connection is automatically closed when the
// code exits the using block.
}
return dataSet;
}
See more details in: https://msdn.microsoft.com/en-us/library/System.Data.OleDb.OleDbParameterCollection(v=vs.110).aspx
It sounds like your trying to use a local database or auto-named database: Here is the syntax for your connection string:
Data Source=(LocalDB)\v11.0;
AttachDbFilename=Your local location here;
Integrated Security=True
Hope that helps.
The problem is you're using System.Data.Sql as the provider, when it should all be coming from System.Data.OleDb;
However, you can use <asp:SqlDataSource> in ASPX, to connect to an Access Database, but that is not the same thing as System.Data.Sql.

Doesn't save added value into database

In Visual Studio (2013) I have added service-based database (Database1.mdf) in my project. I have added in it a table, and via Show Data Table added two rows. Reading data from database works as required. But there is a problem with add value to database. If I while the program is running add value to database and then press "Reading data" it's ok, the data is reading. But If I while the program is still running go to "Show Data Table" and press button "update", I get the error: "This database cannot be imported. It is either an unsupported SQL Server verison or an unsopported database compatibility".
If I press button "update" in "SQL Server Object Explorer" and then go to "Show Data Table" and press button "update", the data is updates, but no added data. Also, after the completion of the program there isn't the added data.
Why?
I have tried to change the properties "Copy To Output Directory" from "Copy always" to "Do not Copy" or "Copy if newer". But it didn't help me. Please help me
Read data:
string strConnectionString = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True";
using (SqlConnection con = new SqlConnection(strConnectionString))
{
try
{
SqlCommand command = new SqlCommand("SELECT [Login] FROM [UsersTable];", con);
con.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
label1.Text = "Last value: " + reader.GetString(0);
}
}
}
catch (SqlException ex)
{
}
Add data:
string strConnectionString = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True";
using (SqlConnection con2 = new SqlConnection(strConnectionString))
{
using (SqlCommand command2 = new SqlCommand())
{
command2.Connection = con2;
command2.CommandType = CommandType.Text;
command2.CommandText = "INSERT INTO [UsersTable] ([Login], [Password]) VALUES (#Login, #Password)";
command2.Parameters.AddWithValue("#Login", textLogin.Text);
command2.Parameters.AddWithValue("#Password", textPassword.Text);
try
{
con2.Open();
command2.ExecuteNonQuery();
}
catch (SqlException)
{
// error here
}
finally
{
con2.Close();
}
}
}
Update
Perhaps the example isn't clear enough for you.
private void SubmitNote(string message)
{
// Ensure parameter isn't null.
if(string.IsNullOrEmpty(message))
return;
// Our Insert Query:
string insert = #"INSERT INTO [Notes] ([Username], [Date], [Message])
VALUES (#Username, #Date, #Message);";
// Define our Connection & Command:
using(SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["db"].ConnectionString))
using(SqlCommand command = new SqlCommand(insert, connection))
{
// Open Connection
connection.Open();
// Define our Command (AddWithValue / Add Approach)
command.Parameters.Add("#Username", SqlDbType.VarChar, 50).Values = User.Identity.Name;
command.Parameters.AddWithValue("#Date", DateTime.Now);
command.Parameters.Add("#Message", SqlDbType.VarChar).Value = message;
// Execute Query:
command.ExecuteNonQuery();
}
}
So anytime I'd like to insert a message to the database I simply call:
SubmitNote("What is love, baby don't hurt me.");
That would execute without any issues, assuming the parameter and connection are valid. You could write an exception helper, but that is above and beyond your issue. One of the problems your potentially having is:
Parameter may be Null
An issue within your Command Text
Potential issue with your Connection String.
Based on the issue you mentioned, a value is Null which means it doesn't contain a valid value. For instance if you do:
String message = String.Empty;
SubmitNote(message);
That would fail, as message doesn't have a value. Hopefully this helps.

Inserting into MySQL database from C# Webforms, give ArgumentException

I'm trying to create a Registration Page using Webforms that'll connect to a MySQL databse and insert the data, but it throws up an ArgumentException (even though I believe I'm following my tutorial exactly) and will not insert the data into the table.
My C# code for the Registration page is thus:
public partial class Registration : System.Web.UI.Page
{
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
String queryStr;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void registerEventMethod(object sender, EventArgs e)
{
registerUser();
}
private void registerUser()
{
String connString =
System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "";
queryStr = "INSERT INTO seniorschema.registration (Password1, Email, FirstName, LastName, Password2, Code)" +
"VALUES('" + PasswordTextBox1.Text +"','"+ EmailTextbox.Text +"','"+ firstNameTextBox.Text+"','"+ LastNameTextBox.Text + "' ,'"+ PasswordTextBox2.Text +"', '"+ CodeTextBox.Text + "' )";
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
cmd.ExecuteReader();
conn.Close();
}
}
And my connection in the WebConfig file is here:
<connectionStrings>
<add name="WebAppConnString"
connectionString="server=localhost;ID=webuser;pwd=password;database=seniorschema;"
providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
Any Help would be most appreciated. Thanks!
I don't know what tutorial you are reading but they should never teach to use string concatenation when building an sql command text.
However, the error you get is from the connectionstring.
You should write
String connString =ConfigurationManager.ConnectionStrings["WebAppConnString"].ConnectionString;
There is also an error in the definition of the connectionstring in the web.config ( a typo?)
It is Uid=.... not ID=....
And here how I would write the code that add the record.
using MySql.Data.MySqlClient;
....
queryStr = #"INSERT INTO seniorschema.registration
(Password1, Email, FirstName, LastName, Password2, Code)
VALUES(#pwd, #email, #first, #last, #pwd2, #code";
using(MySqlConnection conn = new MySqlConnection(connString))
using(MySqlCommand cmd = new MySqlCommand(queryStr, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#pwd",PasswordTextBox1.Text);
cmd.Parameters.AddWithValue("#email",EmailTextbox.Text );
cmd.Parameters.AddWithValue("#first",firstNameTextBox.Text);
cmd.Parameters.AddWithValue("#last",LastNameTextBox.Text );
cmd.Parameters.AddWithValue("#pwd2",PasswordTextBox2.Text );
cmd.Parameters.AddWithValue("#code",CodeTextBox.Text);
int rowAdded = cmd.ExecuteNonQuery();
}
This approach remove the string concatenation with all the complexities required to correctly code the quotes around the values, also removes any possibility of Sql Injection
Finally, but this is really an argument too broad and not immediately linked to your question.
It is a bad practice, from a security standpoint, to store passwords in clear text. If someone could get a copy of or read the registration table, he/she will be able to read the passwords of all users registered. There are proven methods that store an hash of the password to make them unreadable to onlookers

I cannot send/insert data into my new database table using Visual Studio

I am having trouble trying to send my data into my database.
Basically, I am using an ASP.Net Web form already implemented by Visual Studio 2012 (Professional). I have created an extra page called 'users.asps' with only three text boxes (username, full name and email). Then I also created a new database called 'Datatest.mdf' and added ONE table in the database called 'users' which includes three attributes: username (primary key), name and email.
Below is my code for the button on the page. Here is where I want to send all the inputted data into my database table.
protected void Button1_Click(object sender, EventArgs e)
{
string strun = Request.Form["username"];
string strna = Request.Form["name"];
string strem = Request.Form["email"];
OleDbConnection objconnection = null;
OleDbCommand objcmd = null;
string stringconnection = null;
string strSQL = null;
//connection string
stringconnection = "provider=SQLOLEDB;data source=(LocalDb)\\v11.0;Initial Catalog=Datatest; Integrated Security=SSPI;";
objconnection = new OleDbConnection(stringconnection);
objconnection.ConnectionString = stringconnection;
objconnection.Open();
strSQL = "insert into users(username, name, email)values(?,?,?)";
objcmd = new OleDbCommand(strSQL, objconnection);
objcmd.Parameters.Add(new System.Data.OleDb.OleDbParameter("#username", strun));
objcmd.Parameters.Add(new System.Data.OleDb.OleDbParameter("#name", strna));
objcmd.Parameters.Add(new System.Data.OleDb.OleDbParameter("#email", strem));
objcmd.ExecuteNonQuery();
//close connection
objconnection.Close();
Response.Write("Entered Successfully");
}
When I run the form however I am getting an error "OleDbException was unhandled by user code" then says "SQL Server does not exist or access denied" that has an arrow pointing at objconnection.Open();.
Despite where the error is located, I know the problem lies where my string connection is, I just don't know how I can fix it.
stringconnection = "provider=SQLOLEDB;data source=(LocalDb)\\v11.0;Initial Catalog=Datatest; Integrated Security=SSPI;";
For all your connectionstring propblems.
You want to take a look in the sql department of that website.
I think that SQLOLEDB provider doesn't understand the connection string required to use a LocalDB.
(The LocalDB is more recent than SQLOLEDB)
Try to use SQLNCLI11 (The Sql Server Native Client v11)
"provider=SQLNCLI11;data source=(LocalDb)\\v11.0;
Initial Catalog=Datatest; Integrated Security=SSPI;";
However, if you are in the initial stage of developping your application I really suggest to use the SqlClient classes like SqlConnection, SqlCommand etc and leave behind the OleDb and all its limitations. (Like no support for named parameters)
using System.Data.SqlClient;
......
stringconnection = #"Data Source=(LocalDb)\\v11.0;Initial Catalog=Datatest;
Integrated Security=SSPI;";
using(objconnection = new SqlConnection(stringconnection))
{
objconnection.Open();
strSQL = "insert into users(username, name, email)values(#username, #name, #email)";
using(objcmd = new SqlCommand(strSQL, objconnection))
{
objcmd.Parameters.Add(new SqlParameter("#username", strun));
objcmd.Parameters.Add(new SqlParameter("#name", strna));
objcmd.Parameters.Add(new SqlParameter("#email", strem));
objcmd.ExecuteNonQuery();
}
}
Response.Write("Entered Successfully");
Try to visit this link https://www.daniweb.com/software-development/csharp/threads/339949/how-to-establish-a-connection-with-sql-server-using-c
maybe it can help you on your database connection problem :)

How to add/edit/retrieve data using Local Database file in Microsoft Visual Studio 2012

I want to get into developing applications that use databases. I am fairly experienced (as an amateur) at web based database utilization (mysql, pdo, mssql with php and old style asp) so my SQL knowledge is fairly good.
Things I have done already..
Create forms application
Add four text boxes (first name, last name, email, phone)
Added a datagrid control
Created a database connection using 'Microsoft SQL Server Database File (SqlClient)'
Created a table with fields corresponding to the four text boxes.
What I want to be able to do now is, when a button is clicked, the contents of the four edit boxes are inserted using SQL. I don't want to use any 'wrapper' code that hides the SQL from me. I want to use my experience with SQL as much as possible.
So I guess what I am asking is how do I now write the necessary code to run an SQL query to insert that data. I don't need to know the SQL code obviously, just the c# code to use the 'local database file' connection to run the SQL query.
An aside question might be - is there a better/simpler way of doing this than using the 'Microsoft SQL Server Database File' connection type (I have used it because it looks like it's a way to do it without having to set up an entire sql server)
The below is inserting data using parameters which I believe is a better approach:
var insertSQL = "INSERT INTO yourTable (firstName, lastName, email, phone) VALUES (firstName, lastName, email, phone)";
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI; User ID=userid;Password=pwd;"
using (var cn = new SqlCeConnection(connectionString))
using (var cmd = new SqlCeCommand(insertSQL, cn))
{
cn.Open();
cmd.Parameters.Add("firstName", SqlDbType.NVarChar);
cmd.Parameters.Add("lastName", SqlDbType.NVarChar);
cmd.Parameters.Add("email", SqlDbType.NVarChar);
cmd.Parameters.Add("phone", SqlDbType.NVarChar);
cmd.Parameters["firstName"].Value = firstName;
cmd.Parameters["lastName"].Value = lastName;
cmd.Parameters["email"].Value = email;
cmd.Parameters["phone"].Value = phone;
cmd.ExecuteNonQuery();
}
This is selecting data from database and populating datagridview:
var dt = new DataTable();
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI; User ID=userid;Password=pwd;"
using (var cn = new SqlCeConnection(connectionString )
using (var cmd = new SqlCeCommand("Select * From yourTable", cn))
{
cn.Open();
using (var reader = cmd.ExecuteReader())
{
dt.Load(reader);
//resize the DataGridView columns to fit the newly loaded content.
yourDataGridView.AutoSize = true; yourDataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
//bind the data to the grid
yourDataGridView.DataSource = dt;
}
}
This first example is an over view based upon how I think it will be easier to understand but this is not a recommended approach due to vulnerability to SQL injection (a better approach further down). However, I feel it is easier to understand.
private void InsertToSql(string wordToInsert)
{
string connectionString = Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI; User ID=myDomain\myUsername;Password=myPassword;
string queryString = "INSERT INTO table_name (column1) VALUES (" + wordToInsert + ")"; //update as you feel fit of course for insert/update etc
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open()
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand(queryString, connection);
command.ExecuteNonQuery();
connection.Close();
}
}
I would also suggest wrapping it in a try/catch block to ensure the connection closes if it errors.
I am not able to test this but I think it is OK!
Again don't do the above in live as it allows SQL injection - use parameters instead. However, it may be argued it is easier to do the above if you come from PHP background (just to get comfortable).
This uses parameters:
public void Insert(string customerName)
{
try
{
string connectionString = Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI; User ID=myDomain\myUsername;Password=myPassword;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
connection.Open() SqlCommand command = new SqlCommand( "INSERT INTO Customers (CustomerName" + "VALUES (#Name)", connection);
command.Parameters.Add("#Name", SqlDbType.NChar, 50, " + customerName +");
command.ExecuteNonQuery();
connection.Close();
}
catch()
{
//Logic in here
}
finally()
{
if(con.State == ConnectionState.Open)
{
connection.Close();
}
}
}
And then you just change the SQL string to select or add!

Categories