I can insert my data to Excel well, but I have a problem.
Here is a screenshot to illustrate.
I want to see my inserted data just below the last inserted data, but it shows up further down, in the screenshot as shown with a black circle.
Here is my code:
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelfilepath + ";Extended Properties=\"Excel 12.0;ReadOnly=False;HDR=Yes;\"";
OleDbConnection connection = new OleDbConnection(connectionString);
connection.Open();
OleDbCommand command = new OleDbCommand("insert into [EVDS$] ([Tarih], [USD], [EUR]) values('" + DateTime.Now.ToShortDateString() + "','" + textBox3.Text + "','" + textBox4.Text + "')", connection);
command.ExecuteNonQuery();
connection.Close();
Related
Here is the code:
string str = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/charlyn_dale/Documents/Visual Studio 2010/Projects/LMS/WindowsFormsApplication2/Accounts.accdb;Persist Security Info=False");
OleDbCommand conn = new OleDbCommand(str);
con.Open();
string query = "insert into Account ([Username],[Password],FirstName,MiddleName,LastName,Age,Section,Gender,Address,AccountStatus) values('" + txt1.Text + "','" + txt2.Text + "','" + txt4.Text + "','" + txt5.Text + "','" + txt6.Text + "','" + txt7.Text + "','" + txt8.Text + "','" + cmb2.Text + "','" + txt9.Text + "','" + cmb1.Text + "')";
OleDbCommand cmd = new OleDbCommand(query, con);
conn.ExecuteNonQuery();
MessageBox.Show("Registration Success!");
con.Close();
and the error is:
Connection property has not been initialized
There are 3 main issues in your Access DB connection:
OleDbConnection connection string property has not initialized when opening OLE DB connection (note that con is different from conn in this context).
The connection string wrongly assigned to variable conn which declared as OleDbCommand, use OleDbConnection instead.
The connection string data source path seems invalid by using slash sign for directory separator (assuming target file exists in Windows folder), use backslash escape sequence (\\) or single backslash with literal string instead (e.g. #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\......").
Hence, the correct connection sequence should be like this:
string str = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\charlyn_dale\\Documents\\Visual Studio 2010\\Projects\\LMS\\WindowsFormsApplication2\\Accounts.accdb;Persist Security Info=False");
using (OleDbConnection conn = new OleDbConnection(str))
{
conn.Open();
// security tips: better use parameter names to prevent SQL injection on queries
// and put value checking method for all textbox values (sanitize input)
string query = "insert into Account ([Username],[Password],FirstName,MiddleName,LastName,Age,Section,Gender,Address,AccountStatus) values ('" + txt1.Text + "','" + txt2.Text + "','" + txt4.Text + "','" + txt5.Text + "','" + txt6.Text + "','" + txt7.Text + "','" + txt8.Text + "','" + cmb2.Text + "','" + txt9.Text + "','" + cmb1.Text + "')";
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
conn.ExecuteNonQuery();
}
... // other stuff
conn.Close();
}
NB: using statements added due to OLE DB connection should be disposed immediately after usage to free up resources.
Similar issues:
get an error as ExecuteNonQuery:Connection property has not been initialized
ExecuteNonQuery: Connection property has not been initialized (access database)
ExecuteNonQuery: Connection property has not been initialized
I was watching https://www.youtube.com/watch?v=SJ-RyDl5E7U It basically teaches me how to create my update and delete button after following the video my program works just like his!
But there is no "checking" statement for my btnSave, allowing the user to enter duplicated data in the data base if they click more than once shown here
So I was wondering if there is a "checking statement" I can use, like if the IndexNumber (first column) exist there will be a message box showing out saying something like "ID is already exists"
This is my current code for the btnSave
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0; AttachDbFilename=" + Application.StartupPath + "\\GlennTeoDB.mdf; Integrated Security=True;Connect Timeout=30");
con.Open();
SqlCommand cmd = new SqlCommand(#"INSERT INTO GlennTeoStudents (IndexNumber,Name,Age,HandphoneNumber,GPA) VALUES ('" + numIN.Value + "','" + txtName.Text + "','" + txtAge.Text + "','" + txtHP.Text + "','" + numGPA.Value + "')", con);
cmd.ExecuteNonQuery();
con.Close();
As you are using ado.net something like this;
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0; AttachDbFilename=" + "Application.StartupPath" + "\\GlennTeoDB.mdf; Integrated Security=True;Connect Timeout=30");
con.Open();
//get a count records with your index number
SqlCommand validate = new SqlCommand(string.Format("SELECT count(IndexNumber) FROM GlennTeoStudents WHERE IndexNumber = {0}", numIN.Value), con);
int count = (Int32)validate.ExecuteScalar();
if (count == 0)
{
//insert your unqiue index number into a new row
SqlCommand cmd = new SqlCommand(#"INSERT INTO GlennTeoStudents (IndexNumber,Name,Age,HandphoneNumber,GPA) VALUES ('" + numIN.Value + "','" + txtName.Text + "','" + txtAge.Text + "','" + txtHP.Text + "','" + numGPA.Value + "')", con);
cmd.ExecuteNonQuery();
}
else
{
//don't insert it, do something else like return an error
}
con.Close();
You should add an existence check:
SqlCommand cmd = new SqlCommand(#"INSERT INTO GlennTeoStudents (IndexNumber,Name,Age,HandphoneNumber,GPA) VALUES ('" + numIN.Value +
"','" + txtName.Text + "','" + txtAge.Text + "','" + txtHP.Text +
"','" + numGPA.Value + "') WHERE NOT EXISTS ( SELECT * FROM
GlennTeoStudents WHERE IndexNumber = '" + numIN.Value + "')", con);
I have this OleDB code which basically reads an excel file and displays it on to the datagridview after a button click:
string pathConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txtPath.Text + ";Extended Properties=\"Excel 8.0;HDR=Yes;\";";
OleDbConnection conn = new OleDbConnection(pathConn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("SELECT * FROM [" + txtSheet.Text + "$]", conn);
DataTable dt = new DataTable();
myDataAdapter.Fill(dt);
dgvViewDrivers.DataSource = dt;
My question is that how would I make a MySQL Connection out of this OleDB connection string? Please help me.
You need to use MySQL .NET connector
http://dev.mysql.com/downloads/connector/net/
using (MySqlConnection conn = new MySqlConnection("SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";"))
{
using (MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "sql here";
cmd.ExecuteNonQuery();
}
}
Your current code
This
using (vDBCon = new MySqlConnection("SERVER=localhost;Data Source=" + txtPath.Text + ";user=root;PASSWORD= ;"))
txtPath.Text needs to be the name of your database in MySQL. I assume you left the password out. If not you need one.
"SERVER=localhost;Data Source=MyDatabase;user=root;PASSWORD=MyPassword;"
where MyDatabase is the actual name of your database and MyPassword is the password you use to login with
You have to actually be running MySQL Server itself to create and connect to a MySQL database. it doesn't work of a file like Access. If you want something like that just use SQLite.
this
vCmd.CommandText = "SELECT * FROM [" + txtSheet.Text + "$]";
this you will be selecting data from your table in MySQL so it needs to look like
vCmd.CommandText = "SELECT * FROM MyTable";
where MyTable is actually the name of your table in the database
Scenario:
I want to input data from textbox into the database based on microsoft data base (.mdb)
I already searching and find good clue and my result was here.
This Code below was inside command button click event:
using (OdbcConnection conn= new OdbcConnection())
{
conn.ConnectionString = #"Driver={Microsoft Access Driver (*.mdb)};" +
"Dbq=C:\\BlaBlaBla.mdb;Uid=Admin;Pwd=;";
conn.Open();
using (OdbcCommand cmd = new OdbcCommand(
"INSERT INTO TABLENAME (FIELD1,FIELD2,FIELD3) VALUES ('" + txtFIELD1Input.Text + "','" + txtFIELD2Input.Text + "','" + txtFIELDInput.Text + "' )", conn))
{
cmd.ExecuteNonQuery();
}
conn.Close();
}
And when I click the command button, I get unfriendly exception
ERROR [42S02] [Microsoft][ODBC Microsoft Access Driver] Could not find
output table 'TABLENAME'.
That happened when I insert cmd.ExecuteNonQuery. If I didn't insert that, of course nothing happens in my table target.
So what mistakes did I make in that code? What should I do?
"INSERT INTO TABLENAME (FIELD1,FIELD2,FIELD3) VALUES ('" + txtFIELD1Input.Text + "','" + txtFIELD2Input.Text + "','" + txtFIELDInput.Text + "' )", myConnection))
change this into
"INSERT INTO TABLENAME (FIELD1,FIELD2,FIELD3) VALUES ('" + txtFIELD1Input.Text + "','" + txtFIELD2Input.Text + "','" + txtFIELDInput.Text + "' )", Conn))
you define Conn as your connection string not "myConnection"
So i changed to OleDbConnection And My Problem Cleared,
using (OleDbConnectionconn= new OleDbConnection())
{
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\LOSERONE\Documents\DATABASE\Latihan1.mdb";
conn.Open();
using (OleDbCommand cmd = new OleDbCommand (
"INSERT INTO TABLENAME (FIELD1,FIELD2,FIELD3) VALUES ('" + txtFIELD1Input.Text + "','" + txtFIELD2Input.Text + "','" + txtFIELDInput.Text + "' )", conn))
{
cmd.ExecuteNonQuery();
}
conn.Close();
}
Seems, to connected the database must same as the connection string in the properties on the targeted database.
Does anyone can tell me what is the difference OleDbConnection with OdbcConnection in .mdb database file?!
This problem is because sql connection's default database after login is not the same where your table 'TABLENAME' exists. Try to add database name before table like this:
INSERT INTO DBNAME..TABLENAME (FIELD1, FIELD2)
replace your myConnection to Conn
I want to change the value of a column in a SQL Server table from filtered by 2 others columns. But it returns error: Incorrect syntax ",". Here is code:
private void button1_Click(object sender, EventArgs e)
{
string connectionString = #"Data Source=" + System.IO.File.ReadAllText("Server.ini") + ";" + "Initial Catalog=" + "lin2world" + ";" + "User ID=" + System.IO.File.ReadAllText("User.ini") + ";" + "Password=" + System.IO.File.ReadAllText("Password.ini");
string sql = "UPDATE user_item SET amount='" + textBox3.Text + "'WHERE char_id='" + textBox1.Text + "' ,item_type='" + textBox2.Text + "' ";
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "user_item");
connection.Close();
MessageBox.Show("Item Amount Changed");
}
Thank you!
You are missing a space before WHERE.
And you have a comma where you want to use AND.
Change like this:
string sql = "UPDATE user_item SET amount='" + textBox3.Text + "' WHERE char_id='" +
textBox1.Text + "' AND item_type='" + textBox2.Text + "' ";
The sql where conditions will be either combined by using AND or OR so you need to replace the comma ( textBox1.Text + "' ,item_type='" +) with the wanted expression.
Also it would be much better with regard to sql injection, to use command parameters for the values beeing compared and updated.
private void button1_Click(object sender, EventArgs e)
{
string connectionString = #"Data Source=" + System.IO.File.ReadAllText("Server.ini") + ";" + "Initial Catalog=" + "lin2world" + ";" + "User ID=" + System.IO.File.ReadAllText("User.ini") + ";" + "Password=" + System.IO.File.ReadAllText("Password.ini");
string sql = "UPDATE user_item SET amount='" + textBox3.Text + "' WHERE char_id='" + textBox1.Text + "' AND item_type='" + textBox2.Text + "' ";
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "user_item");
connection.Close();
MessageBox.Show("Item Amount Changed");
}
Two mistakes - Space before WHERE and missing AND in WHERE clause
Raj
string sql = "UPDATE user_item SET amount='" + textBox3.Text + "'WHERE char_id='" + textBox1.Text + "' ,item_type='" + textBox2.Text + "' ";
here
,item_type= ',' should be "and" or "or"
You need to add a space between ' and where. Also, you are doing an update and populating a data set? Are you just looking to do an update or are you trying to get data as well?
You should look to use string.Format() here to make it more readable. Also, consider parameterized query as you are leaving yourself open to sql injections. Better still, ditch the dynamic sql and replace with a stored procedure.
Tutorial on String.Format()
If you're not using the dataset, then use ExecuteNonQuery()
private void button1_Click(object sender, EventArgs e)
{
string connectionString = #"Data Source=" + System.IO.File.ReadAllText("Server.ini") + ";" +
"Initial Catalog=" + "lin2world" + ";" + "User ID=" +
System.IO.File.ReadAllText("User.ini") + ";" + "Password=" +
System.IO.File.ReadAllText("Password.ini");
string sql = string.Format("UPDATE user_item SET amount='{0}' WHERE char_id='{1}' AND item_type='{2}'",
textBox3.Text, textBox1.Text, textBox2.Text);
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(sql, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
MessageBox.Show("Item Amount Changed");
}
I highly recommend you not to use this format:
sql = "UPDATE user_item SET amount='" + textBox3.Text + "'WHERE char_id='" + textBox1.Text + "' ,item_type='" + textBox2.Text + "' ";
instead, you should use:
sql = String.format("UPDATE user_item SET amount=%d WHERE char_id=\'%s\' and item_type=\'%s\'",textBox3.Text,textBox1.Text,textBox2.Text);
This form is much more clear to avoid errors.