C# Unable to log data onto database - c#

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

Related

How to use a database connection class in my entire application

I have created a class for the MS Access database connection. It works fine on the majority of the forms within my Winforms app. However, I have a form where the user can add, edit or delete information from the database. I've constructed that part using a string, but when I remove the long database connection string I had there before and replace it with the class I created it throws an exception.
I've tried changing the code by removing the string, but I want to use the string method.
This is the code I have for the delete button click event
string con = (#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source =C:\Users\folder\Desktop\ApplicationFolder\AppName\bin\Debug\DataBase\DatabaseName.accdb");
string Query = "delete from Employees2 where EmployeeName = '" +
this.txtAdminFEmployee.Text + "' ; ";
OleDbConnection ConnectionString = new OleDbConnection(con);
OleDbCommand command = new OleDbCommand(Query, ConnectionString);
OleDbDataReader reader;
try
{
ConnectionString.Open();
reader = command.ExecuteReader();
DialogResult result = MessageBox.Show("Employee Deleted Successfully",
"Information",
MessageBoxButtons.OK, MessageBoxIcon.Information);
while (reader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
ConnectionString.Close();
This is the database class I created
using System.Data.OleDb;
namespace AppName
{
class OledbConnect
{
public OleDbConnection con;
public void Connection()
{
con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\DatabaseName.accdb");
}
}
}
I need to know how to use the database class in that string. I've tried different ways but nothing works. I am still new to c# and Google is not really returning anything I can use. Thanks
Your initial code works, but confusion is evident in the naming of variables.
string con = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source =C:\Users\folder\Desktop\ApplicationFolder\AppName\bin\Debug\DataBase\DatabaseName.accdb";
(I've taken the un-needed parentheses off the declaration; it's just a string.)
Calling that string 'con' is a bit confusing. I'd call it 'connectionString', or maybe 'cs' for short.
OleDbConnection ConnectionString = new OleDbConnection(con);
OleDbCommand command = new OleDbCommand(Query, ConnectionString);
OK, so you correctly create an OleDbConnection, passing the connection string (con) to its constructor. This is good. But you confusingly call it ConnectionString. It isn't the connection string; it's the connection, and your code thereafter uses it correctly.
So that works. Confusing for a human to read because of the mis-naming of variables, but the compiler doesn't care what their names are - it knows very well that ConectionString is an OleDbConnection and doesn't feel any of the cognitive dissonance that I do when I look at it.
If you rename the variables in the original code as I've suggested, and then copy that code into your class (BTW, I'd just call it DbConnection; it's current name is very close to another class name which might also be confusing), paying attention to what each statement does and what each variable represents then you should be good to go.

How to update Oracle CLOB column with long string using C# and Oracle Data Access Client

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.

Error during insert of record from asp.net into SQL Server database

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.

Blank values in SqlDatasource

After setting up my SqlDataSource on another page to display the values, they come up as 2 blanks for the 2 times I entered test values on the comments page.
I think I'm missing something in getting them into the table in the SQL Server database value?
I'm not sure what information is needed here, so please inform me.
Thanks in advance
EDIT #1 for user request for CODE
protected void btnSend_Click(object sender, EventArgs e)
{
Page.Validate("vld2");
SendMail();
lblMsgSend.Visible = true;
//SQL Server Database
SqlConnection conn; //manages connection to database
SqlCommand cmd; //manages the SQL statements
string strInsert; //SQL INSERT Statement
try
{
//create a connection object
conn = new SqlConnection("Data Source=localhost\\sqlexpress;" +
"Initial Catalog=RionServer;" +
"Integrated Security=True;");
//Build the SQL INSERT Document
strInsert = "INSERT INTO CommentsAdmin (Name,Phone,Email,Comments)"
+ "VALUES(#Name,#Phone,#Email,#Comments);";
//associate the INSERT statement with the connection
cmd = new SqlCommand(strInsert, conn);
//TELL the SqlCommand WHERE to get the data from
cmd.Parameters.AddWithValue("Name", txtName.Text);
cmd.Parameters.AddWithValue("Phone", txtPhone.Text);
cmd.Parameters.AddWithValue("Email", txtEmail.Text);
cmd.Parameters.AddWithValue("Comments", txtComment.Text);
//open the connection
cmd.Connection.Open();
//run the SQL statement
cmd.ExecuteNonQuery();
//close connection
cmd.Connection.Close();
//display status message on the webpage
lblMsgSend.Text = "Thank you for the comment! Please hit the 'Return to Main Page' to return to the Main Page!";
}
catch (Exception ex)
{
lblMsgSend.Text = ex.Message;
}
txtPhone.Text = "";
txtEmail.Text = "";
txtName.Text = "";
txtComment.Text = "";
}
EDIT #2
The values seems to be empty for the Name, Phone, Email, and Comments in the database and when I test the query, so I think it's registering the entries, just not taking the values into the SQL?
EDIT #3
Due to a suggestion by coder and rs, I've done what they've said. And now I get this error.
"String or binary data would be truncated. The statement has been terminated."
The code has been updated as well.
EDIT #4
This question is a follow up for SQL Server Error, 'Keyword not supported 'datasource'.
Remove all the "" similar to this txtPhone.Text = ""; before entering values to SQL as Server you're entering null values to that. So even if you give some values to the textbox it takes predefined NULL values and it dosen't enter either of them.

How to properly initialize a .NET OleDbConnection object and its ConnectionString property?

This is my C# code to connect and work with an Access database.
using System.Data.OleDb;
var cb = new OleDbCommandBuilder(da);
DataRow dRow = ds1.Tables["Customer"].NewRow();
dRow[0] = textBox1.Text;
dRow[1] = textBox2.Text;
dRow[2] = textBox3.Text;
ds1.Tables["Customer"].Rows.Add(dRow);
da.Update(ds1, "Customer");
con.Close();
MessageBox.Show("Entry added");
But the line da.Update(ds1,"Customer");, throws an exception:
The ConnectionString property has not been initialized.
I'm not following your question too well, but here's some sample code that may help you figure out whatever it is that you are trying to do.
For clarity: The database is named "MyDb.accdb" and has a table named "Customer" which has two fields "Name" and "Phone". This example assumes the database lives in the same directory as the executable.
private void AddCustomer(string customerName, string customerPhone)
{
string name = customerName;
string phone = customerPhone;
// An easy way to determine the connection string to your database is to open the database from Visual Studio's 'Server Explorer'.
// Then, from Server Explorer, view the Properties of the database - in the Properties you will see the "Connection String".
// You can/should replace the arbitrary part of the path with "|DataDirectory|".
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|MyDb.accdb;Persist Security Info=True";
// Create your sql query in a string variable
string cmdText = string.Format("INSERT INTO Customer(Name, Phone) VALUES('{0}','{1}');", name, phone);
// Use the 'using' statement on your connection so that the resource is managed properly
using (System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection(connString))
{
// Here's where/how we fire off the INSERT statement
OleDbCommand cmd = new OleDbCommand(cmdText, connection);
connection.Open();
cmd.ExecuteNonQuery();
}
}

Categories