I am getting an error while retrieving connections strings from app.config file using vs2010 C#.net/sql server. My codes are below can some one pls help me in this.Can someone pls help me to fix this issue. I am working in client server env accessing DB from server.
private void btnSendEmailtoDB_Click(object sender, EventArgs e)
{
string connectionStrings= GetDatabaseConnection().ToString();
//if (GetDatabaseConnection() != null)
//{
foreach (DataRow dr in dt.Rows)
{
InsertEmailData(connectionStrings, dr["Subject"].ToString(), dr["Content-Description"].ToString(), dr["From"].ToString(), dr["To"].ToString(), Convert.ToDateTime(dr["DateSent"].ToString()), loginTextBox.Text);
}
//}
}
private string GetDatabaseConnection()
{
var connectionString = ConfigurationManager.ConnectionStrings["emailDownloadsManagement"].ConnectionString;
return connectionString;
}
private void InsertEmailData(string connectionString, string emailSubject, string emailBodyDescription, string emailsFrom, string emailsTo, DateTime emailsDate, string emailsUser)
{
// define INSERT query with parameters
string query = "INSERT INTO dbo.tblEmailDownload (emailMessageSubject, emailMessageBodyDescription, emailFrom, emailTo, emailDate, emailUser) " +
"VALUES (#emailMessageSubject, #emailMessageBodyDescription, #emailFrom, #emailTo, #emailDate, #emailUser) ";
// create connection and command
using (SqlConnection cn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, cn))
{
// define parameters and their values
cmd.Parameters.Add("#emailMessageSubject", SqlDbType.VarChar, 500).Value = emailSubject;
cmd.Parameters.Add("#emailMessageBodyDescription", SqlDbType.VarChar, 5000).Value = emailBodyDescription;
cmd.Parameters.Add("#emailFrom", SqlDbType.VarChar, 50).Value = emailsFrom;
cmd.Parameters.Add("#emailTo", SqlDbType.VarChar, 50).Value = emailsTo;
cmd.Parameters.Add("#emailsDate", SqlDbType.DateTime).Value = emailsDate;
cmd.Parameters.Add("#emailUser", SqlDbType.VarChar, 50).Value = emailsUser;
// open connection, execute INSERT, close connection
//if (cmd.Connection.State == ConnectionState.Open)
//{
// cmd.Connection.Close();
//}
cn.Open(); // the error is here saying ServerVersion 'cn.ServerVersion' threw an exception of type 'System.InvalidOperationException' string {System.InvalidOperationException} and saying connection is closed
cmd.ExecuteNonQuery();
cn.Close();
}
}
my app.config file details are below looks like everything is correct but there is an error
<configuration>
<connectionStrings>
<add name="emailDownloadsManagement" connectionString="Data Source = SERVER;Initial Catalog=emails;User Id=administrator;Password=password;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
and here is the more detailed error description.
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
one more thing found can some one pls correct
Hi All, while debugging found this format of connection string which looks not fine fine because of \ can someone pls help me to correct "Data Source=SERVER;Initial Catalog=emails;User Id=abcxyz\administrator;Password=password" is this userid with \ is causing not to open connection. Pls help... and i have tried changing from windows authentication to sql authentication but error is same and exists now also. pls help...
The error you are getting indicates it cannot connect to the database server using the connection string you have provided. Since you are using integrated security it will try and connect as the user that is set under the iis app pool, you cannot provide a windows username and password in the connection string. If you don't use integrated authentication then you can supply a username and password but this needs to be a SQL server user not a windows user.
first u check u r able to login to database from current loginid and password. and check the database name.
and after that check in webconfig for connectionstring(correct name).
ConfigurationManager.ConnectionStrings["emailDownloadsManagement"].ConnectionString.ToString()
and after that try your above code.
I think you need to insert the exact same amount of parameter values into your table......... #emailMessageID could be the culprit as the insert statement does not look right. Also try putting your whole insert statement on one line without the '+' join. Connection looks ok but I can't really say without being at your end.
hope this helps
Christian
Related
I want to connect to SQL Server 2016 using Windows authentication.
I am using C# with this connection string
Server=192.168.1.12,14331;Database=master;Integrated Security=true;Timeout=30
or
Server=serversql\newinstance;Database=master;Integrated Security=true;Timeout=30
The error is a timeout connection.
When using connection with SQL Server authentication like this:
Server=192.168.1.12,14331;Database=master;User Id=***;Password=****;Timeout=30
everything is ok.
Source code C#
var constr = "<connection string>";
using (var connection = new SqlConnection(constr))
{
var command = connection.CreateCommand();
command.CommandType = CommandType.Text;
command.CommandText = "SELECT 1";
command.CommandTimeout = 0;
connection.Open();
command.ExecuteNonQuery();
}
But when I am using SQL Server Management Studio to check connection to the SQL Server instance with Windows authentication, it is ok. Using alias or Ip address does not help the error.
I don't understand why I get this error ...
Help me please! Thanks you everyone!
UPDATE:
If I use connection 1 with IP and port, there is an error:
Login failed. The login is from an untrusted domain and cannot be used
with Windows
UPDATE:
Instance SQL installed on other PC the same network LAN with My PC.
I'm checked Log Viewer on PC install instance SQL but no record log.
I'm not sure it works for you, but you can try it:
SqlConnection cnn;
public connect(){
string strConnect = #"Data Source=192.168.1.12,14331;Network Library=DBMSSOCN;Initial Catalog=master;User ID=****;Password=*****";
cnn = new SqlConnection(strConnect);
try
{
cnn.Open();
}
catch(Exception)
{
// connect failed
}
}
public void ExeQuery(string query){
// query="select * from tblA"
SqlCommand sqlCmd = new SqlCommand(query,cnn);
sqlCmd.ExecuteNonQuery();
sql.Dispose();
}
I am new to net developing and have managed to work my way through a lot of questions I have had just by looking through the forums.
It appears that the issue that I am having is something that a number of others have had I have found that they are all different and just haven't for the life of me been able to work through it.
I am trying to insert player registration details into database but when I try to invoke the wcf server it am met with the exception type on my conn.Open():
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code.
In addition I am using the build it sql server and the connection string used is one from properties on the database.
I am not too sure how to proceed.
public string playerRegistration(playerDetails playerInfo)
{
string Message;
using (SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\\Users\\Daniel\\documents\\visual studio 2013\\Projects\\Prac4\\WebApplication1\\App_Data\\ADODatabase.mdf;Integrated Security=True"))
{
conn.Open();
using (var cmd = new SqlCommand("INSERT into Player(pid, pfname, plname, pphone, paddress, pdob) VALUES (#pid, #pfname, #plname, #pphone, #paddress, #pdob)", conn))
{
cmd.Parameters.AddWithValue("#pid", playerInfo.Pid);
cmd.Parameters.AddWithValue("#pfname", playerInfo.Pfname);
cmd.Parameters.AddWithValue("#plname", playerInfo.Plname);
cmd.Parameters.AddWithValue("#pphone", playerInfo.Pphone);
cmd.Parameters.AddWithValue("#paddress", playerInfo.Paddress);
cmd.Parameters.AddWithValue("#pdob", playerInfo.Pdob);
int result = cmd.ExecuteNonQuery();
if (result == 1)
{
Message = " Details inserted successfully";
}
else
{
Message = " Details not inserted successfully";
}
conn.Close();
return Message;
}
}
}
Make sure to use #".." (a verbatim string literal) with connection strings to avoid simple escaping mistakes.
The code shown with "..\v.." contains a vertical tab escape which produces an invalid connection string. There is no compiler error because the string literal is syntactically valid although the resulting string is incorrect.
Recommended fix with a verbatim string literal and elimination of double slashes:
#"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\Users\Daniel.."
Alternative fix (note the \\v):
"Data Source=(LocalDB)\\v11.0;AttachDbFilename=c:\\Users\\Daniel.."
The problem is in your connection string
"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\\Users\\Daniel\\documents\\visual studio 2013\\Projects\\Prac4\\WebApplication1\\App_Data\\ADODatabase.mdf;Integrated Security=True"
Search the internet to find the required format for SQL Server. You do not need an MDF file name, here's a helpful link:
https://www.connectionstrings.com/sql-server/
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();
I created a database (without user or password) as a service-based database.
Now I'm trying to insert to a database, but there is a error "Login failed for user"
I have this code:
string J_connetionString1 = null;
SqlConnection J_connection1;
SqlDataAdapter J_adapter1 = new SqlDataAdapter();
string J_sql1 = null;
J_connetionString1 = #"Data Source=.\SQLEXPRESS;Initial Catalog=J_InsData";
J_connection1 = new SqlConnection(J_connetionString1);
J_sql1 = "update instinfo set instinfoNAME = textBox2.text where instinfoID ='1'";
try
{
J_connection1.Open();
J_adapter1.UpdateCommand = J_connection1.CreateCommand();
J_adapter1.UpdateCommand.CommandText = J_sql1;
J_adapter1.UpdateCommand.ExecuteNonQuery();
MessageBox.Show("Row updated !! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
i can't comment so i edited the Q.
this error appeared by using this code
error :
system.Data.sqlclint.sqlexpection(0x80131904)
cannot open database "J_InsData" request by the login. the login faild
login failed for user J-PC\J
code:
J_connetionString1 = #"Data Source=.\SQLEXPRESS;Initial Catalog=J_InsData;Trusted_Connection=True;Integrated Security=SSPI";
You need to tell SQL Server which user credentials to use for a connection.
Hence you should provide a user id and password of SQL Server user in your connection string.
Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;
On the other hand if the SQL erver is configured to accept windows domain users, you can use Integrated Security=SSPI or Trusted_Connection=True in the connection string.
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
Server=myServerAddress;Database=myDataBase;Integrated Security=SSPI;
Have you tried adding the following to your connection string?
Integrated Security=True
or
Integrated Security=SSPI
which is pretty mcuh the same as True.
This LINK might be useful for you as well.
Hi I would like to know how I should connect to the external SQL Server database in C# , .NET ?
For example if I have there parameters :
SQL info
Url to get to database (throughout browser also): Sqlweb.companyname.com
Database username: username
Server: Dcms-xxx
Databasename: databaseName
Databasepassword: password
?
I know how to connect to internal : Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + System.AppDomain.CurrentDomain.BaseDirectory + "..\\Files\\MapPlaces\\Database.mdb;";
But what about external ?
I have tried :
string nowConString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Sqlweb.companyname.com;Initial Catalog = databaseName; User Id = Username; Password = Password;";
System.Data.OleDb.OleDbConnection dbcon = new System.Data.OleDb.OleDbConnection(nowConString);
string sql = "SELECT * FROM XXXTable";
dbcon.Open();
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(sql, dbcon);
System.Data.OleDb.OleDbDataReader reader;
reader = cmd.ExecuteReader();
ScriptStuff.Append("Reader created!<br/>");
while (reader.Read())
{
string companyName = reader.GetValue(1).ToString();
ScriptStuff.Append(companyName+"<br/>");
}
Did not work ! Thank you for your help !
Edited from comments:
Yes that was one my mistake, thanks. Since first one was access and YES second is SQL Server. And it is SQL Server 2005. But I am new to .net and all that... I have found first one and second one in that connectionstring.com but I could not find or understand how to use that for this one ...
Could you help, and just post hole connection ? Thanks – Vilius 7 mins ago
I mean do I still need to use OleDB ? should there be "Provider=Microsoft.Jet.OLEDB.4.0;" in that connection string ? Where do i post what (server (that Dcms-xxx), or url of the sql server (sqlweb.companyname.com))? THANKS FOR YOUR HELP ! –
I would add a connectionString to my app/web.config.
<connectionStrings>
<add name="AspnetdbConnectionString"
connectionString="Data Source=<databaseadress>;Initial Catalog=<database>;User Id=<user>;Password=password>"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
The above example is how you specify an connectionstring for a MSSQL connection, and below a way to use this connectionstring.
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AspnetdbconnectionString"].ConnectionString))
{
cn.Open();
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.Text;
cm.CommandText = "SELECT * FROM ...";
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{
while (dr.Read())
{
// do stuff
}
}
}
}
Are you sure that it's a SQL Server database that you are trying to connect to?
Your "internal" example connects to a Microsoft Access database (OLEDB provider and database file extension .mdb)
If your external database is really a SQL Server database, the recommended way is using SqlConnection, SqlDataReader and so on instead of OleDbConnection etc.
Or, if you really want to use OleDb, you need a different connection string.
See connectionstrings.com (for SQL Server 2008, 2005 or 2000, depending what you're trying to connect to).
I would highly recommend taking a look at:
http://www.connectionstrings.com/
It's a quick, "in you face" treatment of the subject of connection strings for all major databases.