C#: SQL Server Connection String - c#

I am trying to use a button that will add to my two columns in my database. I have placeholder values in there currently but will eventually be using 2 pop ups to read in those values.
My question is: how do I get the connection string? I don't know what to put there or where to get that data.
private void button_AddPartNumber_Click(object sender, EventArgs e)
{
string cmdString = "INSERT INTO Part_Numbers (Part_Number, Barcode_Number) VALUES (#val1, #val2)";
string connectionString = "I DONT KNOW WHAT TO PUT HERE";
using (SqlCommand connection = new SqlCommand(connectionString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = connectionString;
comm.CommandText = cmdString;
comm.Parameters.AddWithValue("#val1", "L-0G004-0830-xx"); //placeholder value
comm.Parameters.AddWithValue("#val2", "asdf1234"); // placehold value
}
}
} // end button_AddPartNumber_Click()

Well, what database are you using? For example, SQLServer? Oracle? MySQL?
In SQLServer, at least, the connection string is defined in the web.config, or app.config, and has syntax similar to the following:
<appSettings>
<add key="ConnectionStringName" value="AppName"/>
</appSettings>
<connectionStrings>
<add name="AppName" connectionString="Data Source=DataSourceName; Initial Catalog=DataBaseName; user id=UserID; password=Password" providerName="System.Data.SqlClient"/>
</connectionStrings>
Something like that. There's probably something I'm missing, but without testing it out in your code, I'm blanking on what that might be.
This how you extract the connection string from your code if the connection string is properly set in the web.config:
var connectionString = ConfigurationManager.ConnectionStrings["AppName"].ConnectionString;

Related

Connection string reference not set to an instance of an object

This is a noob question but I have been stuck here for a few hours so I need to get passed this. I have this Windows App that performs a simple function. It makes a trip to the DB and checks if a specific record exists and if it does then perform some operation. However it just doesn't want to read the connection string - it comes as null all the time. I keep getting null every time I initialize my connection string. What could I be doing wrong. I only have one connection string named App.config.
Class File:
private class ClassA
{
private string myConnectionString = "";
private SqlConnection mySQLConnection;
private SqlCommand mySQLCommand;
private int CheckIfSerialNumberExists(UInt64 ColumnToCheck)
{
int countResult = 0;
myConnectionString = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString; //I get an object reference null here when the compiler executes this line. I have been using this structure for years and never got any issues
using (mySQLConnection = new SqlConnection(myConnectionString))
{
string procName = "SELECT Count(*) ColumnName FROM Table WHERE ColumnName='" + ColumnToCheck + "'";
mySQLCommand = new SqlCommand(procName, mySQLConnection);
mySQLConnection.Open();
countResult = (int)mySQLCommand.ExecuteScalar();
}
return countResult;
}
private void someFunc()
{
//Test value: 5
if(CheckIfSerialNumberExists(5) > 0)
{
//Don't do anything
}
else
{
//Save to DB
}
}
}
Config File:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="ConnectionStringName"
connectionString="Data Source=ServerName;Initial Catalog=DatabaseName;Persist Security Info=True;User ID=**;Password=****"
providerName="System.Data.SqlClient" />
</connectionStrings>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1"/></startup>
</configuration>
So here is the quick fix:
In my windows app I am referencing a class library project. I had only added the connection string in that project. I added it to my windows app project and there we go, all was working. Really feel like an idiot.

C# Insert into database, no error and data is not inserted into database

I'm attempting to insert some data into my local SQL database. The command seems to run successfully and I'm not getting any errors, but for some reason the data is not being inserted into the database. Have I forgotten something?
public void RegisterUser(string fName, string lName, string email, string password)
{
string conStr = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
using (SqlConnection openCon = new SqlConnection(conStr))
{
string saveUser = "INSERT into Users (firstName,lastName,email,password,isAdmin) VALUES (#firstName,#lastName,#email,#password,#isAdmin)";
using (SqlCommand querySaveUser = new SqlCommand(saveUser))
{
querySaveUser.Connection = openCon;
querySaveUser.Parameters.AddWithValue("#firstName", fName);
querySaveUser.Parameters.AddWithValue("#lastName", lName);
querySaveUser.Parameters.AddWithValue("#email", email);
querySaveUser.Parameters.AddWithValue("#password", password);
querySaveUser.Parameters.AddWithValue("#isAdmin", 1);
openCon.Open();
querySaveUser.ExecuteNonQuery();
}
}
}
Connection String:
<connectionStrings>
<add name="DatabaseConnectionString" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\App_Data\Database.mdf;Integrated Security=True;"
providerName="System.Data.SqlClient" />
update:
SOLVED! I was trying to output to another directory for some reason. Ended up recreating the database which solved the issue.
Do
int affected = querySaveUser.ExecuteNonQuery();
and set a debug point and watch affected value.
According to MSDN "If a rollback occurs, the return value is also -1."
In case you are debugging a copy of your DB is created in bin/Debug folder, thus you might be checking different DB. Check this - https://visualstudiomagazine.com/blogs/tool-tracker/2012/05/dealing-with-local-databases-or-why-your-updates-dont-stick.aspx
I check your code and its working fine in my system but i have changed your connection string so please modified your connection string as mine then check i hope your problem solved
public void RegisterUser(string fName, string lName, string email, string password)
{
string conStr = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
using (SqlConnection openCon = new SqlConnection(conStr))
{
string saveUser = "INSERT into Users (firstName,lastName,email,password,isAdmin) VALUES (#firstName,#lastName,#email,#password,#isAdmin)";
using (SqlCommand querySaveUser = new SqlCommand(saveUser))
{
querySaveUser.Connection = openCon;
querySaveUser.Parameters.AddWithValue("#firstName", fName);
querySaveUser.Parameters.AddWithValue("#lastName", lName);
querySaveUser.Parameters.AddWithValue("#email", email);
querySaveUser.Parameters.AddWithValue("#password", password);
querySaveUser.Parameters.AddWithValue("#isAdmin", 1);
openCon.Open();
querySaveUser.ExecuteNonQuery();
}
}
}
Connection String: web.config
<connectionStrings>
<add name="DatabaseConnectionString" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database.mdf; Initial Catalog=Database.mdf; Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
It might help someone looking for Entity Framework Core or ASP.NET Zero related solution.
In my case I was using ASP.NET Zero boiler plate templates for ASP.NET Core and it was not inserting into the database. After a few minutes exploration, I found out that ASP.NET Zero does not immediately execute the ef queries on db rather it inserts rows at end of the unit of work.
Usually, it fails to insert if there is an exception it will log that to Logs table, you can see the latest logs with exceptions if they were failed.
If you want to execute the queries immediately, you can force it to save changes by calling the SaveChanges() method like this:
await CurrentUnitOfWork.SaveChangesAsync();

Error populating dropdownlist from SQL Database

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)
)
);

how to write connectionstring in web.config file

My code works well but after trying to host it. Its database always response with the null value . I failed to host it. and now when i try to debug in my PC its also have the same problem of null response.
my class file and its scalar query code.
public Object ExecuteScalarQuery(String sp)
{
String _ConnString = System.Configuration.ConfigurationManager.ConnectionStrings["rfid"].ConnectionString;
// string _ConnString = ConfigurationManager.ConnectionStrings["rfid"].ConnectionString;
SqlConnection myConnection = new SqlConnection(_ConnString);
SqlCommand cmd = new SqlCommand(sp, myConnection);
Object result = 0;
try
{
myConnection.Open();
result = cmd.ExecuteScalar();
}
catch (Exception ex)
{
//if (myConnection.State == ConnectionState.Open)
// myConnection.Close();
}
finally
{
//if (myConnection.State == ConnectionState.Open)
// myConnection.Close();
}
return result;
}
And web.config file having connectionstring
<connectionStrings>
<add name="rfid" connectionString="Data Source=CHINTAN-PC\SQLEXPRESS;Initial Catalog=msdb;Integrated Security=True " providerName="System.Data.SqlClient"/>
while doing step by step debugging its connectionstring look like this which is not being working.
"Data Source=CHINTAN-PC\\SQLEXPRESS;Initial Catalog=msdb;Integrated Security=True "
One thing to check is that results are being returned by your stored procedure. I copied your code, made a table and a stored procedure to query all records from it, and it returned null when the table was empty and the value of the first column of the first row when I added a couple records.
add the property 'pooling'.
<add name="rfid" connectionString="Data Source=CHINTAN-PC\SQLEXPRESS;Initial Catalog=msdb;Integrated Security=True; pooling=false;" providerName="System.Data.SqlClient"/>
go to server explorer, select you data base. in the right pane(Properties) copy connection string and paste it. if that doesn't work. go to sql management studio. its your windows authentication and sql authentication problem. make a new sql authentication login and give userid="" and password="" like "sa" and "sa123" in the connection string.
Use toString to retrieve the string value
String _ConnString = System.Configuration.ConfigurationManager.ConnectionStrings["rfid"].ConnectionString.toString();

Getting sql connection string from web.config file

I am learning to write into a database from a textbox with the click of a button. I have specified the connection string to my NorthWind database in my web.config file. However I am not able to access the connection string in my code behind.
This is what I have tried.
protected void buttontb_click(object sender, EventArgs e)
{
System.Configuration.Configuration rootwebconfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Mohtisham");
System.Configuration.ConnectionStringSettings constring;
constring = rootwebconfig.ConnectionStrings.ConnectionStrings["northwindconnect"];
SqlConnection sql = new SqlConnection(constring);
sql.Open();
SqlCommand comm = new SqlCommand("Insert into categories (categoryName) values ('" + tb_database.Text + "')", sql);
comm.ExecuteNonQuery();
sql.Close();
}
I get a tooltip error for
SqlConnection sql = new SqlConnection(constring);
as
System.data.SqlClient.Sqlconnection.Sqlconnection(string) has some invalid arguments.
I want to load the connection string from the web.config in constring
You can simply give a Name to your ConnectionString in web.config file and do this:
web.config:
<add name="ConnectionStringName" connectionString=YourServer"; Initial Catalog=YourDB; Integrated Security=True"/>
Code Behind:
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringName"].ToString());
That's because the ConnectionStrings collection is a collection of ConnectionStringSettings objects, but the SqlConnection constructor expects a string parameter. So you can't just pass in constring by itself.
Try this instead.
SqlConnection sql = new SqlConnection(constring.ConnectionString);
try this
readonly SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["northwindconnect"].ToString());
I will suggests you to create a function rather than directly access the web.config file as follow
public static string GetConfigurationValue(string pstrKey)
{
var configurationValue = ConfigurationManager.AppSettings[pstrKey];
if (!string.IsNullOrWhiteSpace(configurationValue))
return configurationValue;
throw (new ApplicationException(
"Configuration Tag is missing web.config. It should contain <add key=\"" + pstrKey + "\" value=\"?\"/>"));
}
And use this function in you application

Categories