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();
}
}
Related
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 am having trouble trying to send my data into my database.
Basically, I am using an ASP.Net Web form already implemented by Visual Studio 2012 (Professional). I have created an extra page called 'users.asps' with only three text boxes (username, full name and email). Then I also created a new database called 'Datatest.mdf' and added ONE table in the database called 'users' which includes three attributes: username (primary key), name and email.
Below is my code for the button on the page. Here is where I want to send all the inputted data into my database table.
protected void Button1_Click(object sender, EventArgs e)
{
string strun = Request.Form["username"];
string strna = Request.Form["name"];
string strem = Request.Form["email"];
OleDbConnection objconnection = null;
OleDbCommand objcmd = null;
string stringconnection = null;
string strSQL = null;
//connection string
stringconnection = "provider=SQLOLEDB;data source=(LocalDb)\\v11.0;Initial Catalog=Datatest; Integrated Security=SSPI;";
objconnection = new OleDbConnection(stringconnection);
objconnection.ConnectionString = stringconnection;
objconnection.Open();
strSQL = "insert into users(username, name, email)values(?,?,?)";
objcmd = new OleDbCommand(strSQL, objconnection);
objcmd.Parameters.Add(new System.Data.OleDb.OleDbParameter("#username", strun));
objcmd.Parameters.Add(new System.Data.OleDb.OleDbParameter("#name", strna));
objcmd.Parameters.Add(new System.Data.OleDb.OleDbParameter("#email", strem));
objcmd.ExecuteNonQuery();
//close connection
objconnection.Close();
Response.Write("Entered Successfully");
}
When I run the form however I am getting an error "OleDbException was unhandled by user code" then says "SQL Server does not exist or access denied" that has an arrow pointing at objconnection.Open();.
Despite where the error is located, I know the problem lies where my string connection is, I just don't know how I can fix it.
stringconnection = "provider=SQLOLEDB;data source=(LocalDb)\\v11.0;Initial Catalog=Datatest; Integrated Security=SSPI;";
For all your connectionstring propblems.
You want to take a look in the sql department of that website.
I think that SQLOLEDB provider doesn't understand the connection string required to use a LocalDB.
(The LocalDB is more recent than SQLOLEDB)
Try to use SQLNCLI11 (The Sql Server Native Client v11)
"provider=SQLNCLI11;data source=(LocalDb)\\v11.0;
Initial Catalog=Datatest; Integrated Security=SSPI;";
However, if you are in the initial stage of developping your application I really suggest to use the SqlClient classes like SqlConnection, SqlCommand etc and leave behind the OleDb and all its limitations. (Like no support for named parameters)
using System.Data.SqlClient;
......
stringconnection = #"Data Source=(LocalDb)\\v11.0;Initial Catalog=Datatest;
Integrated Security=SSPI;";
using(objconnection = new SqlConnection(stringconnection))
{
objconnection.Open();
strSQL = "insert into users(username, name, email)values(#username, #name, #email)";
using(objcmd = new SqlCommand(strSQL, objconnection))
{
objcmd.Parameters.Add(new SqlParameter("#username", strun));
objcmd.Parameters.Add(new SqlParameter("#name", strna));
objcmd.Parameters.Add(new SqlParameter("#email", strem));
objcmd.ExecuteNonQuery();
}
}
Response.Write("Entered Successfully");
Try to visit this link https://www.daniweb.com/software-development/csharp/threads/339949/how-to-establish-a-connection-with-sql-server-using-c
maybe it can help you on your database connection problem :)
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
I am trying to past an Ms.Excel table column names into a combo box. i use the function bellow to do the activity but i get an exception look like this
'Metadata$' is not a valid name. Make sure that it does not include invalid characters or punctuation and that it is not too long.
Here is the code
'Metadata$' is not a valid name. Make sure that it does not include invalid characters or punctuation and that it is not too long
private void connection(String path)
{
string connectionString = string.Format(Thread.CurrentThread.CurrentCulture, "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=YES;'",path);
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand command = connection.CreateCommand())
{
command.CommandText = #"SELECT [File], [ItemName], [ItemDescription], [Photographer name], [Date], [Environment site] FROM [Metadata$]";
connection.Open();
using (DbDataReader dr = command.ExecuteReader())
{
if (dr.HasRows)
{
while (dr.Read())
{
cmb.Items.Add(dr[0].ToString());
}
}
}
connection.Close();
}
}
}
Note - i use openfiledialog to get the path of excel file
i used fallowing sql command instead of using one on the code.
"SELECT column_name from information_schema.columns where table_name = 'BigData' Order by ordinal_position";
which gives me below exception.
"The Microsoft Access database engine could not find the object 'columns'. Make sure the object exists and that you spell its name and the path name correctly. If 'columns' is not a local object, check your network connection or contact the server administrator."
i would like to correct this errors. both or at least single one.
thank you.
I want to get into developing applications that use databases. I am fairly experienced (as an amateur) at web based database utilization (mysql, pdo, mssql with php and old style asp) so my SQL knowledge is fairly good.
Things I have done already..
Create forms application
Add four text boxes (first name, last name, email, phone)
Added a datagrid control
Created a database connection using 'Microsoft SQL Server Database File (SqlClient)'
Created a table with fields corresponding to the four text boxes.
What I want to be able to do now is, when a button is clicked, the contents of the four edit boxes are inserted using SQL. I don't want to use any 'wrapper' code that hides the SQL from me. I want to use my experience with SQL as much as possible.
So I guess what I am asking is how do I now write the necessary code to run an SQL query to insert that data. I don't need to know the SQL code obviously, just the c# code to use the 'local database file' connection to run the SQL query.
An aside question might be - is there a better/simpler way of doing this than using the 'Microsoft SQL Server Database File' connection type (I have used it because it looks like it's a way to do it without having to set up an entire sql server)
The below is inserting data using parameters which I believe is a better approach:
var insertSQL = "INSERT INTO yourTable (firstName, lastName, email, phone) VALUES (firstName, lastName, email, phone)";
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI; User ID=userid;Password=pwd;"
using (var cn = new SqlCeConnection(connectionString))
using (var cmd = new SqlCeCommand(insertSQL, cn))
{
cn.Open();
cmd.Parameters.Add("firstName", SqlDbType.NVarChar);
cmd.Parameters.Add("lastName", SqlDbType.NVarChar);
cmd.Parameters.Add("email", SqlDbType.NVarChar);
cmd.Parameters.Add("phone", SqlDbType.NVarChar);
cmd.Parameters["firstName"].Value = firstName;
cmd.Parameters["lastName"].Value = lastName;
cmd.Parameters["email"].Value = email;
cmd.Parameters["phone"].Value = phone;
cmd.ExecuteNonQuery();
}
This is selecting data from database and populating datagridview:
var dt = new DataTable();
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI; User ID=userid;Password=pwd;"
using (var cn = new SqlCeConnection(connectionString )
using (var cmd = new SqlCeCommand("Select * From yourTable", cn))
{
cn.Open();
using (var reader = cmd.ExecuteReader())
{
dt.Load(reader);
//resize the DataGridView columns to fit the newly loaded content.
yourDataGridView.AutoSize = true; yourDataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
//bind the data to the grid
yourDataGridView.DataSource = dt;
}
}
This first example is an over view based upon how I think it will be easier to understand but this is not a recommended approach due to vulnerability to SQL injection (a better approach further down). However, I feel it is easier to understand.
private void InsertToSql(string wordToInsert)
{
string connectionString = Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI; User ID=myDomain\myUsername;Password=myPassword;
string queryString = "INSERT INTO table_name (column1) VALUES (" + wordToInsert + ")"; //update as you feel fit of course for insert/update etc
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open()
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand(queryString, connection);
command.ExecuteNonQuery();
connection.Close();
}
}
I would also suggest wrapping it in a try/catch block to ensure the connection closes if it errors.
I am not able to test this but I think it is OK!
Again don't do the above in live as it allows SQL injection - use parameters instead. However, it may be argued it is easier to do the above if you come from PHP background (just to get comfortable).
This uses parameters:
public void Insert(string customerName)
{
try
{
string connectionString = Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI; User ID=myDomain\myUsername;Password=myPassword;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
connection.Open() SqlCommand command = new SqlCommand( "INSERT INTO Customers (CustomerName" + "VALUES (#Name)", connection);
command.Parameters.Add("#Name", SqlDbType.NChar, 50, " + customerName +");
command.ExecuteNonQuery();
connection.Close();
}
catch()
{
//Logic in here
}
finally()
{
if(con.State == ConnectionState.Open)
{
connection.Close();
}
}
}
And then you just change the SQL string to select or add!