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/
Related
EDIT: It only took a week but I eventually found out the issue, primarily due to pure luck and another error with a more specific fix.
The issue was with the connStr I had made, which for some reason on this machine gave me the error randomly of "System.ArgumentException: Keyword not supported: 'datasource'." during runtime. I then found out a fix for that was to rename the connStr as follows:
connStr = #"server = (server name); Initial Catalog = AutoTestDB; Integrated Security = true";
Should you have this error as I have, try that method of connection. END EDIT
I'm currently working on Automated Testing using Katalon Automated Testing, essentially Selenium for Chrome, and whenever I'm attempting to add the results of the test to our Test Results Database the SQL Exception "A network-related or instance-specific error occurred while establishing a connection to SQL Server. " keeps popping up. TCP/IP is open, as is firewall and remote connections, and I have the SQL-SMS open and running while I run the database with the SQL connection.
However it only happens whenever I'm using a certain machine to access the database which is stored within the machine itself, as it is with every other machine that I use and they all work perfectly fine. The only difference I can think of for this machine is that it uses SQL Express while all the others that I use have the full version of Microsoft SQL-SMS-17.
It's a genuine case of "It works on my machine", except with the caveat that it works on several others and even across different users as we are all working on this automated testing, this machine is the lone exception for this code not working, with the only difference being that it uses SQL Express which should be accounted for with the \\SQLExpress.
C# code with SQL connetions to edit the values into an already made table within the database.
public void testDBAdd(String testName, Boolean pass, String testComment)
{
SqlConnection con;
SqlDataAdapter daAutoTest;
DataSet dsAutoTestDB = new DataSet();
SqlCommandBuilder cmdBAutoTest;
String connStr, sqlAutoTest;
connStr = #"datasource = .\\sqlexpress; Initial Catalog = AutoTestDB; Integrated Security = true";
con = new SqlConnection(connStr);
sqlAutoTest = #"SELECT * FROM TestResults";
daAutoTest = new SqlDataAdapter(sqlAutoTest, connStr);
cmdBAutoTest = new SqlCommandBuilder(daAutoTest);
daAutoTest.FillSchema(dsAutoTestDB, SchemaType.Source, "AutoTest");
daAutoTest.Fill(dsAutoTestDB, "AutoTest");
foreach (DataRow drAutoTest in dsAutoTestDB.Tables["AutoTest"].Rows)
{
if (pass == true && drAutoTest["testName"].ToString() == testName)
{
drAutoTest.BeginEdit();
drAutoTest["testName"] = testName;
drAutoTest["testResult"] = 1;
drAutoTest["testComment"] = testComment;
drAutoTest.EndEdit();
daAutoTest.Update(dsAutoTestDB, "AutoTest");
}
else if (pass == false && drAutoTest["testName"].ToString() == testName)
{
drAutoTest.BeginEdit();
drAutoTest["testName"] = testName;
drAutoTest["testResult"] = 0;
drAutoTest["testComment"] = "Exception: " + testComment;
drAutoTest.EndEdit();
daAutoTest.Update(dsAutoTestDB, "AutoTest");
}
}
}
Code which runs the actual test and gathers if it has passed or failed due to the presence of certain elements, in this case is a certain page displayed when the user logs in and clicks a button.
public void settingTest<TestNumber>()
{
IWebDriver driver = new ChromeDriver();
ChromeOptions options = new ChromeOptions();
options.AddArguments("--start-maximized");
driver = new ChromeDriver(options);
String testName = "<Test Number>", testComment = "";
Boolean pass = false;
try
{
settingsLogin(driver);
settingsClick(driver);
Assert.IsTrue(driver.FindElement(ElementLocator).Displayed);
if (driver.FindElement(ElementLocator).Displayed == true)
{
testComment = "Pass";
pass = true;
testDBAdd(testName, pass, testComment);
}
}
catch (Exception ex)
{
testComment = "" + ex.TargetSite + "" + ex.Message;
testDBAdd(testName, pass, testComment);
}
finally
{
driver.Close();
}
}
Not sure, but I think your connection string has an extraneous backslash. You've prefaced the string with a "#" but then used "\\" in the Data Source. You might also try "(localdb)\SQLExpress" as the data source.
It only took a week but I eventually found out the issue, primarily due to pure luck and another error with a more specific fix. The issue was with the connStr I had made, which for some reason on this machine gave me the error randomly of "System.ArgumentException: Keyword not supported: 'datasource'." during runtime. I then found out a fix for that was to rename the connStr as follows:
connStr = #"server = (server name); Initial Catalog = AutoTestDB; Integrated Security = true";
Should you have this error as I have, try that method of connection. And thanks to the users who tried to help in both the comments of the post and in the answers section of this post.
I'm trying to update a CLOB column in my database with a long string containing the HTML contents of an email. There are 18,000 characters in the record I'm having an issue with.
The below code will work if I set the html variable to "short string". But if I try to run the code with the long 18,000 character HTML string, I get this error: "Oracle.DataAccess.Client.OracleException ORA-22922: nonexistent LOB value ORA-02063: preceding line from ((servername))"
public static void UpdateHtmlClob(string html, string taxId,string un, string pw)
{
using (OracleConnection conn = new OracleConnection())
{
try
{
conn.ConnectionString = "User Id=" + un + ";Password=" + pw + ";Data Source=server.com;";
conn.Open();
OracleCommand cmd = new OracleCommand();
string indata = html;
cmd.CommandText = "UPDATE table1 SET HTML_BODY = :clobparam";
OracleParameter clobparam = new OracleParameter("clobparam", OracleDbType.Clob, indata.Length);
clobparam.Direction = ParameterDirection.Input;
clobparam.Value = indata;
cmd.Parameters.Add(clobparam);
cmd.Connection = conn;
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
conn.Close();
}
}
}
Before you edited your code to reflect my answer, there were two problems with your code that I saw.
Firstly, you need to use a colon in your command text to tell Oracle that clobparam is a bind variable, not a column name:
cmd.CommandText = "UPDATE table1 SET HTML_BODY = :clobparam";
Secondly, you were not setting the database connection anywhere on the command. Which connection should the command be using? In your situation you have only one connection but more generally it may be possible to have more than one connection open. Add the line
cmd.Connection = connection;
or alternatively create the command using
OracleCommand cmd = connection.CreateCommand();
Of course, it would be nice if Oracle.DataAccess returned an error message that gave you the slightest hint that this was what you were doing wrong.
Anyway, now that you've edited your question to include the critical detail ORA-02063: preceding line from ((servername)), which tells us that you are using a database link, all I can really do is echo what I wrote in the comment: connect direct to the remote database to transfer LOB data, don't use a database link.
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.
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
I am trying to log everytime a search is conducted on my program. The log is located on an access database. When i try to log the name of the user and computer name i receive an error and the data does not populate on my access database. Below is the code i have any support would be greatly appreciated.
private void logdata()
{
string User="";
string PCName="";
DateTime now = DateTime.Now;
User = WindowsIdentity.GetCurrent().Name.ToString();
PCName = SystemInformation.ComputerName.ToString();
try
{
string constr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\\data.accdb;Jet OLEDB:Database Password=test";
string cmdstr = "Insert into SearchLog(Location,SearchDate,SearchTime,User,PCName)Values(#a,#b,#c,#d,#e)";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
com.Parameters.AddWithValue("#a", txtLocNo.Text);
com.Parameters.AddWithValue("#b", now.ToString("d"));
com.Parameters.AddWithValue("#c", DateTime.Now.ToString("HH:mm:ss"));
com.Parameters.AddWithValue("#d", User);
com.Parameters.AddWithValue("#e", PCName);
com.ExecuteNonQuery();
con.Close();
}
catch (Exception eX)
{
string ErrorPrompt = "Select Ok and your search will continue";
MessageBox.Show(ErrorPrompt, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
USER is a keyword in MS-Access Jet SQL. If you have a field or a table with that name then you should enclose it in square brackets when passing a command text from an application.
string cmdstr = #"Insert into SearchLog(Location,SearchDate,SearchTime,[User],PCName)
Values(#a,#b,#c,#d,#e)";
I suggest, if this is possible, to change the name of that field to something different to avoid future errors of this kind.
Also keep in mind that AddWithValue creates the parameter with a datatype taken from the value part.
You have two fields that seems to be dates but you create a parameter of string type (ToString()).
OLE DB.NET Framework Data Provider uses positional parameters that are
marked with a question mark (?) instead of named parameters.
MSDN
see also https://stackoverflow.com/a/8124103/1271037