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();
Related
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();
I got this error during insert of data into a SQL Server database
Here is my code in button click event
try
{
string ConnString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=\\MOD03-PC\\Share Folder mod03\\amts\\amtsfuelconsuption\\AmtsFuelConsumption\\AmtsFuelConsumption\\App_Data\\AmtsDatabse.mdf;Integrated Security=True;Connect Timeout=900,providerName=System.Data.SqlClient";
SqlConnection con = new SqlConnection(#ConnString);
SqlCommand cmd = new SqlCommand("InsertBodyTypeMaster", con);
cmd.CommandTimeout = 0;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("bodytypename", txtBTname.Text.ToString());
con.Open();
int k = cmd.ExecuteNonQuery();
if (k != 0)
{
lblmessage.Text = "Record Inserted Succesfully into the Database";
lblmessage.ForeColor = System.Drawing.Color.CornflowerBlue;
}
con.Close();
con.Dispose();
}
catch (Exception ex)
{
lblmessage.Text = ex.ToString();
}
I see a few things wrong;
As mentioned, you need to change your Connect Timeout=900, to Connect Timeout=900;
You need to delete providerName=System.Data.SqlClient part since you already using the .NET provider for SQL Server. Provider names for .NET are implicit based on the implementing class and not needed to specified in the connection string. When you delete this, you will not need ; at the end of Connect Timeout=900; anymore
Use using statement to dispose your connection and command automatically instead of calling Close or Dispose methods manually.
Don't use AddWithValue as much as you can. It may generate unexpected and surprising results sometimes. Use Add method overload to specify your parameter type and it's size.
Final connection string should be as;
string ConnString = "Data Source=(LocalDB)\v11.0,AttachDbFilename=\\MOD03-PC\\Share Folder mod03\\amts\\amtsfuelconsuption\\AmtsFuelConsumption\\AmtsFuelConsumption\\App_Data\\AmtsDatabse.mdf;Integrated Security=True;Connect Timeout=900";
You have a comma and not a semi-colon after the 900 in the connect timeout property in the connection string.
Cause your connection string is total weird. remove those ; and replace them with ,. Also, make sure you spell them properly. It should be like
string ConnString = "Data Source=(LocalDB)\v11.0,AttachDbFilename=\\MOD03-PC\\Share Folder mod03\\amts\\amtsfuelconsuption\\AmtsFuelConsumption\\AmtsFuelConsumption\\App_Data\\AmtsDatabse.mdf,Integrated Security=True,Connect Timeout=900;providerName=System.Data.SqlClient";
Also the below line
SqlConnection con = new SqlConnection(#ConnString);
It should be
SqlConnection con = new SqlConnection(ConnString);
You are calling Dispose() inside try block which is big blunder as shown below. Either use Using(...) block (or) finally block
try
{
....
con.Close();
con.Dispose();
}
Should be
finally
{
con.Close();
con.Dispose();
}
Looks like it's time you should start reading through documentation.
string connectionString = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
SQLiteConnection connString = new SQLiteConnection(connectionString);
using (var command = connString.CreateCommand())
{
try
{
connString.SetPassword(ConfigurationManager.AppSettings["password1"]);
connString.Open();
connString.ChangePassword((String)null);
connString.ChangePassword(ConfigurationManager.AppSettings["password2"]);
connString.Close();
connString.Dispose();
}
catch (Exception e)
{
Console.Write(e.Message + "\n" + e.StackTrace);
}
}
I'm trying to test SQLite by having a simple console application. I'm using an app.config file to read passwords and connection string from. The code is able to set the password the very first time it runs but if I open the connection and try to change password by calling ChangePassWord() method, the password is not changed. I also try to set password to null and then reset it to some new password, but that doesn't work either.
The error is
File Opened that is not a database file. File is encrypted or is not a database
Some other people have the same problem: ChangePassword method problem.
I'm not 100% sure. But for some reason reading the connection string from the app.config could have some bearing on it. I took out the connection string and decided to hardcode it like so
SQLiteConnection connString = new SQLiteConnection("data source=\".\\SomeDatabase\"");
before was like so:
<connectionStrings>
<add name="connection"
connectionString="data source=".\SomeDatabase""
providerName="System.Data.SQLite" />
</connectionStrings>
Hope this helps somebody
The connection name 'MySqlServer' was not found in the applications configuration or the connection string is empty.
So, I have a page with a panel that will display when the connection in the web config is found and the connection is valid; using a try/catch as long as the add name"VALUE" is in the config connection strings if the server data is bad the page will load and the panel is set to invisible... I need to be able to handle the following...
If the named value in this case MySqlServer is used in the aspx; aspx.cs but not found in the config I do not want the error to occur; connection name was not found.... I just want to not show the panel like when the SqlConnection.Open fails when the name is found but data is bad...
aspx
<asp:SqlDataSource runat="server" ID="allowedIPsSqlDataSource"
ConnectionString="<%$ ConnectionStrings:MySqlServer %>"
aspx.cs
string connectionString = ConfigurationManager.ConnectionStrings["MySqlServer"].ToString();
SqlConnection SqlConnection = new SqlConnection(connectionString);
SqlCommand SqlCommand = new SqlCommand();
try
{
SqlConnection.Open();
config
<connectionStrings>
<add name="NotMySqlServer" providerName="System.Data.SqlClient" connectionString="server=TEST\SQL2005;database=ADB;Integrated Security=True"/>
<add name="NotMy2SqlServer" providerName="System.Data.SqlClient" connectionString="server=TEST\SQL2005;database=ADB;Integrated Security=True"/>
</connectionStrings>
You can try :
if(ConfigurationManager.ConnectionStrings["MySqlServer"] == null) throw ...
If you're using .NET 4.5+ and have access to C# 6.0, you can make use of the null conditional operator (?) to try and get the connection string without automatically throwing an exception:
string connectionString = ConfigurationManager.ConnectionStrings["MySqlServer"]?.ConnectionString;
//------------------------------------------------------------------------HERE-^-HERE-------------
if (string.IsNullOrWhiteSpace(connectionString))
{
// Don't even bother trying to open the connection.
// Log the error and either rethrow the exception (throw;) or exit from your current context (return;).
//return;
//throw;
}
// If your code has made it this far, it means you have a valid connection string. Now try to use it.
using (var sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
using (var sqlCommand = new SqlCommand)
{
// Do stuff.
}
}
You can check if there are any connections strings by using count.
var count = ConfigurationManager.ConnectionStrings.Count;
if (count > 0)
{
//There is at least more then one connection string.
}
Update
public static class Extension
{
public static bool HasConnectionString(this ConnectionStringSettingsCollection value, string key)
{
try
{
return value[key].ConnectionString.Length > 0;
}catch
{
return false;
}
}
}
You can use the extension as follow.
if (ConfigurationManager.ConnectionStrings.HasConnectionString("MySqlServer"))
{
//If true you know there is a valid connectionstring.
}
If I'm letting Visual Studio take care of adding an SQL Server database to an existing project, it adds the connection string to app.config. How can I use use THAT connection string to make my own connections and datasets?
Use the ConfigurationManager.AppSettings to read the connection string when required.
For example, if you opening a SQL Connection, use the assign the "Connection String" property to the value retrieved from ConfigurationManager.AppSettings ("MyConnectionString")
If it is placed in the appropriate section in the app config file, then you can use ConfigurationManager.ConnectionStrings to retrieve it as well.
Read more here http://msdn.microsoft.com/en-us/library/ms254494.aspx
Place the connection string in your app.config then use
ConfigurationManager.ConnectionStrings[str].ConnectionString.ToString();
to get the connection string.
For example:
private string GetConnectionString(string str)
{
//variable to hold our return value
string conn = string.Empty;
//check if a value was provided
if (!string.IsNullOrEmpty(str))
{
//name provided so search for that connection
conn = ConfigurationManager.ConnectionStrings[str].ConnectionString.ToString();
}
else
//name not provided, get the 'default' connection
{
conn = ConfigurationManager.ConnectionStrings[ConnStr].ConnectionString;
}
//return the value
return conn;
}
Then you can reference the connection using ado.net or Linq
For Example:
your app.config would contain an entry like:
<connectionStrings>
<add name="nameofConnString" connectionString="Data Source=SQLDATA;Initial Catalog="nameofdatabase";Persist Security Info=True;User ID=username;Password=password;Connection Timeout=30;Pooling=True; Max Pool Size=200" providerName="System.Data.SqlClient"/>
'
Then you could call
conStr = GetConnectionString("nameofConnString")
With Ado.net
You could then establish the connection with:
sqlConn = new SqlConnection(conStr);
sqlConn.Open();
Or with Linq
LinqData ld = new LinqData();
DataContext dataContext = new DataContext(ld.GetConnectionString(sqlConn));
where LinqData is a class that contains the GetConnectionString() method.
Well, both of those helped get me on the right track. I found this quite simple, yet highly annoying. The solution I used was:
using System.Configuration;
add a reference System.configuration
create a new connection with SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabaseConnectionFromApp.Config"].ConnectionString)