ALTER TABLE in Access database from C# - c#

I need to add datagridview data to a MS Access table, at the same time add a column into that table and update the column as well. please help me, I keep getting an error that says Syntax error in field definition and then says No value given for one or more required parameters.
private void button1_Click(object sender, EventArgs e)
{
string myConnectionString = " ";
myConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/game/Desktop/3rd year/2nd Semester/INYM 328/EmployeeAttendanceRegister/EmployeeAttendanceRegister/EmployeeAttendanceRegister.accdb";
OleDbConnection myConnection = new OleDbConnection(myConnectionString);
string col1 = dataGridView1[0, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string col2 = dataGridView1[1, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string col3 = dataGridView1[2, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string col4 = dataGridView1[3, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string col5 = dataGridView1[4, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string col6 = dataGridView1[5, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string col7 = dataGridView1[6, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string myInsertQuery = "INSERT INTO Attendance VALUES('" + col1 + "','" + col2 + "','" + col3 + "','" + col4 + "','" + col5 + "','" + col6 + "','" + col7 + "')";
OleDbCommand myCommand = new OleDbCommand(myInsertQuery);
myCommand.Connection = myConnection;
myConnection.Open();
try
{
myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
myConnection.Close();
{
string myConn = " ";
myConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/game/Desktop/3rd year/2nd Semester/INYM 328/EmployeeAttendanceRegister/EmployeeAttendanceRegister/EmployeeAttendanceRegister.accdb";
OleDbConnection myCon = new OleDbConnection(myConn);
string myInsert = "ALTER TABLE Attendance ADD COLUMN SignIn";
OleDbCommand myCom = new OleDbCommand(myInsert);
myCom.Connection = myCon;
myCon.Open();
try
{
myCom.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
myCon.Close();
}
{
string myString = " ";
myString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/game/Desktop/3rd year/2nd Semester/INYM 328/EmployeeAttendanceRegister/EmployeeAttendanceRegister/EmployeeAttendanceRegister.accdb";
OleDbConnection myConnect = new OleDbConnection(myString);
string Insert = "UPDATE Attendance SET SignIn = '" + dateTimePicker1.Value + "'";
OleDbCommand myComm = new OleDbCommand(Insert);
myComm.Connection = myConnect;
myConnect.Open();
try
{
myComm.ExecuteNonQuery();
MessageBox.Show("Successfully Signed IN");
frmhomepage previousForm = new frmhomepage();
previousForm.Show();
this.Hide();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
myConnect.Close();
}
}

I keep getting an error that says Syntax error in field definition
That's probably because the ALTER TABLE statement
ALTER TABLE Attendance ADD COLUMN SignIn
does not specify the column type. Based on the UPDATE command that follows, you probably meant
ALTER TABLE Attendance ADD COLUMN SignIn DATETIME
However, there are other problems with your code, too:
Why are you trying to ALTER TABLE after every button click? Once you've changed the structure of the [Attendance] table you don't need to do it again.
You are trying to pass a date/time value delimited with single quotes ('). Access SQL normally expects date/time values to be delimited with hash marks (#).
Instead of "gluing SQL statements together" you should use parameterized queries to help you avoid delimiter problems (see above) and protect you from SQL Injection.

Related

C# Updating excel database and inserting record while adding items

so I have this program which when I press a button inserts a record into an excel spreadsheet with, the columns, being , customer, product, weight, dateTime. Now I want to be able to update a record if the same customer, and product occurs, but I also want to add the previous weight field with the new field, and update the time.
The problem is i'm not sure how to modify my update statement to do this.
// Load data from database, and Update database if filed already exists
DataSet ds = new DataSet();
string insertquery = "SELECT * FROM [Sheet1$] where [Customer] = '" + lblcustomername + " ' ";
OleDbConnection myConnection = new OleDbConnection(OutputDatabaseConnectionString); //define new connection object
OleDbDataAdapter mydataadapter = new OleDbDataAdapter(insertquery, myConnection); //define data adaptor and select column data from spreadsheet
mydataadapter.Fill(ds);
int i = ds.Tables[0].Rows.Count;
// If item exists in database, update it
if (i > 0)
{
try
{
System.Data.OleDb.OleDbConnection myConnection2; //create new connection object
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
String sql = null;
myConnection2 = new System.Data.OleDb.OleDbConnection(OutputDatabaseConnectionString); //define connection string
myConnection2.Open();
myCommand.Connection = myConnection2;
sql = "UPDATE [Sheet1$] SET [Net Weight(Kg)]= '" + textBox1.Text + "' WHERE [Customer] = '" + lblcustomername + "'";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
myConnection2.Close();
myConnection2.Close(); //close connection
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
// if it doesn't exist update database
try
{
System.Data.OleDb.OleDbConnection myConnection1; //create new connection object
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
String sql = null;
myConnection1 = new System.Data.OleDb.OleDbConnection(OutputDatabaseConnectionString); //define connection string
myConnection1.Open();
myCommand.Connection = myConnection1;
sql = sql = "INSERT INTO [Sheet1$] ([Customer],[Product],[Net Weight(Kg)], [DateTime]) VALUES('" + lblcustomername.Text + "','" + lblproductname.Text + "','" + textBox1.Text + "','" + (DateTime.Now).ToString() + "')";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
myConnection1.Close();
myConnection1.Close(); //close connection
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}

C# for ASP.NET: Errors from added code

I'm supposed to take some code from my professor and add it to the code I have, but I'm experiencing issues with the function I was told to include and I'm not really sure how I can resolve this issue. I've read some of the other questions that were posted already, but I can't really be sure those are the same thing.
ERROR RESOLVED: Were brackets missing and mistyped variables & method flying around (provided by answer below!)
Error 1: Expected class, delegate, enum, interface, or struct
Error 2: Expected class, delegate, enum, interface, or struct
Error 3: Type or namespace definition, or end-of-file expected
Error 4: clsDataLayer' does not contain a definition for 'SavePersonnel'
Error 5: clsDataLayer' does not contain a definition for 'GetPersonnel'
This was supposed to be an add in and move on kind of deal--not sure if it's my code that's the issue or the code supplied. How do I fix this?
Code Provided: Error 1, 2, & 3
// ERROR OCCURS at bool
public static bool SavePersonnel(string Database, string FirstName, string LastName,
string PayRate, string StartDate, string EndDate)
{
bool recordSaved;
try {
// ERROR 2 OCCURS HERE after new !!!!!
OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + Database);
conn.Open();
OleDbCommand command = conn.CreateCommand();
string strSQL;
// Add your comments here
strSQL = "Insert into tblPersonnel " +
"(FirstName, LastName, PayRate, StartDate, EndDate) values ('" +
FirstName + "', '" + LastName + "', " + PayRate + ", '" + StartDate +
"', '" + EndDate + "')";
// Add your comments here
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
// Add your comments here
command.ExecuteNonQuery();
// Add your comments here
conn.Close();
recordSaved = true;
} //<-- ERROR 3 is at this curly bracket
catch (Exception ex) {
recordSaved = false;
}
return recordSaved;
}
Code Provided: Error 4
// ERROR AFTER clsDataLayer.
if (clsDataLayer.SavePersonnel(Server.MapPath("PayrollSystem_DB.accdb"),
Session["txtFirstName"].ToString(),
Session ["txtLastName"].ToString(),
Session ["txtPayRate"].ToString(),
Session ["txtStartDate"].ToString(),
Session ["txtEndDate"].ToString()))
{
txtVerifiedInfo.Text = txtVerifiedInfo.Text +
"\nThe information was successfully saved!";
}
else
{
txtVerifiedInfo.Text = txtVerifiedInfo.Text +
"\nThe information was NOT saved.";
}
Code Provided: Error 5
if (!Page.IsPostBack)
{
//Declare the Dataset
dsPersonnel myDataSet = new dsPersonnel();
//ERROR AFTER clsDataLayer.
myDataSet = clsDataLayer.GetPersonnel(Server.MapPath("PayrollSystem_DB.accdb"));
//Set the DataGrid to the DataSource based on the table
grdViewPersonnel.DataSource = myDataSet.Tables["tblPersonnel"];
//Bind the DataGrid
grdViewPersonnel.DataBind();
Additional Code adding, required for Error 5:
// This function retrieves all data from tblPersonnel table
public static dsPersonnel GetPersonnel (string Database, string strSearch)
{
dsPersonnel DS;
OleDbConnection SqlConn;
OleDbAdapter sqlDA;
//Opens OleDbConnection
sqlConn = new OleDBConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + Database);
//Employee Search (procured from video, add in later?
if (strSearch == null || strSearch == "")
{
sqlDA = new OleDbDataAdapter("Select * from tblPersonnel", sqlConn);
}
else
{
sqlDA = new OleDbAdapter("Select '' from tblPersonnel where LastName = '" + strSearch + "'", sqlConn);
}
//Sets Value of DS
DS = new dsPersonnel();
//Fills Table with Data
sqlDA_Fill(DS.tblPersonnel);
//Return value
return DS;
}//End Function: Public static dsPersonnel GetPersonnel
Error 1, 2 & 3
Expected class, delegate, enum, interface, or struct
In C#, methods should always be part of a class.
In your case, you have your method flying around without a parent, so the compiler will complain with this error.
To fix this, define your method inside a class:
// C# class
public class clsDataLayer
{
// This functions insert data into tblPersonnel table
public static bool SavePersonnel(string Database, string FirstName, string LastName, string PayRate, string StartDate, string EndDate)
{
bool recordSaved;
try
{
OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + Database);
conn.Open();
OleDbCommand command = conn.CreateCommand();
string strSQL;
// Add your comments here
strSQL = "Insert into tblPersonnel " +
"(FirstName, LastName, PayRate, StartDate, EndDate) values ('" + FirstName + "', '" + LastName + "', " + PayRate + ", '" + StartDate + "', '" + EndDate + "')";
// Add your comments here
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
// Add your comments here
command.ExecuteNonQuery();
// Add your comments here
conn.Close();
recordSaved = true;
}
catch (Exception ex)
{
recordSaved = false;
}
return recordSaved;
}
// This function retrieves all data from tblPersonnel table
public static dsPersonnel GetPersonnel (string Database, string strSearch)
{
dsPersonnel DS;
OleDbConnection SqlConn;
OleDbAdapter sqlDA;
//Opens OleDbConnection
sqlConn = new OleDBConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + Database);
//Employee Search (procured from video, add in later?
if (strSearch == null || strSearch == "")
{
sqlDA = new OleDbDataAdapter("Select * from tblPersonnel", sqlConn);
}
else
{
sqlDA = new OleDbAdapter("Select '' from tblPersonnel where LastName = '" + strSearch + "'", sqlConn);
}
//Sets Value of DS
DS = new dsPersonnel();
//Fills Table with Data
sqlDA_Fill(DS.tblPersonnel);
//Return value
return DS;
}
//End Function: Public static dsPersonnel GetPersonnel
}
Error 4 & 5
clsDataLayer' does not contain a definition for 'SavePersonnel'
This is clearly related to the previous error.
Since SavePersonnel was wrongly declared, the compiler complains it does not exist.
Once we solve errors 1, 2 & 3, the errors 4 & 5 should disappear too.

Using ExecuteReader to return a primary key

How Do I Find the ID from the first query and return this value so it can be inserted into query2? This is the code that needs done when a user completes a form on front end. I need to populate two tables and they will relate through the ID "StoryID" which is a primary key that is automatically created.
protected void Upload2_Click(object sender, EventArgs e)
{
userStoryForm.Visible = false;
info.Text = "You have successfully added a new user story.";
String connectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
String usernameData = username.Text.ToString();
int captureProjectID = Convert.ToInt32(Request.QueryString.Get("ProjectID"));
String storyno = StoryNoTextBox.Text;
String userstory = StoryTextTextBox.Text;
//Create connection
SqlConnection myConnection = new SqlConnection(connectionString);
//open connection
myConnection.Open();
String query = "INSERT INTO UserStories (StoryNo, StoryText, ProductOwner, ProjectID) " +
"VALUES ('" + storyno + "','" + userstory + "','" + usernameData + "','" + captureProjectID + "')" +
"SELECT SCOPE_IDENTITY() AS StoryID;";
SqlCommand myCommand = new SqlCommand(query, myConnection);
// Call GetOrdinal and assign value to variable.
SqlDataReader reader = myCommand.ExecuteReader();
int StoryIDData = reader.GetOrdinal("StoryID");
// Use variable with GetString inside of loop.
while (reader.Read())
{
Console.WriteLine("StoryID={0}", reader.GetString(StoryIDData));
}
// Call Close when done reading.
reader.Close();
//insert productowner, projectID and storyID into ProductBacklog table
String query2 = "INSERT INTO ProductBacklog (ProductOwner, ProjectID, StoryID) VALUES ('" + usernameData + "', #returnProjectID,'" + StoryIDData + "')";
SqlCommand myCommand2 = new SqlCommand(query2, myConnection);
myCommand2.Parameters.AddWithValue("#returnProjectID", captureProjectID);
//close connection
myConnection.Close();
}
}
Most important - use parameters in your SQL command. Never concatenate strings like that. You're asking for an SQL injection attack.
string query = #"
INSERT INTO UserStories (StoryNo, StoryText, ProductOwner, ProjectID)
VALUES (#storyno, #userstory, #usernameData, #captureProjectID)
SELECT CAST(SCOPE_IDENTITY() AS INT)";
SqlCommand myCommand = new SqlCommand(query);
myCommand.Parameters.Add("#storyno", DbType.String).Value = storyno;
...
To get the returned id, use ExecuteScalar():
int StoryIDData = (int)myCommand.ExecuteScalar();
Also, you don't dispose your resources correctly. If an exception is thrown in the method, the SQLConnection will not be closed. You should put it in a using statement.

Syntax error in INSERT statement (access database)

I think I got the insert syntax but I always got this error. When I try different projects that are similar, it works just fine. Can you help me?
private void addbtn_Click(object sender, EventArgs e)
{
if (idkaryawantxt.Text != "")
{
string q = "insert into Table1 (Nama,No_Identitas,Alamat,Lahir,Tanggal_Lahir,Telepon,Divisi,Aktif,Password) values ('" + namakaryawantxt.Text.ToString() + "','" + identitastxt.Text.ToString() + "','" + alamattxt.Text.ToString() + "','" + lahirtxt.Text.ToString() + "','" + tgllahirtxt.Text.ToString() + "','" + tlpntxt.Text.ToString() + "','" + divisitxt.Text.ToString() + "','" + aktiftxt.Text.ToString() + "','" + passwordtxt.Text.ToString() + "')";
dosomething(q);
}
}
private void dosomething(String q)
{
try
{
connect.Open();
command.CommandText = q;
command.ExecuteNonQuery();
connect.Close();
loaddata();
}
catch (Exception e)
{
connect.Close();
MessageBox.Show(e.Message.ToString());
}
}
//REFRESH
private void loaddata()
{
datakaryawan.AllowUserToAddRows = false;
datakaryawan.Rows.Clear();
datakaryawan.Refresh();
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\C# Project\minor\Karyawan.accdb;Persist Security Info=False;";
connect.Open();
command.Connection = connect;
command.CommandText = "SELECT * FROM Table1";
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
datakaryawan.Rows.Add();
datakaryawan.Rows[datakaryawan.Rows.Count - 1].Cells["ID_Karyawan"].Value = reader[0].ToString();
datakaryawan.Rows[datakaryawan.Rows.Count - 1].Cells["Nama_Karyawan"].Value = reader[1].ToString();
datakaryawan.Rows[datakaryawan.Rows.Count - 1].Cells["No_Identitas"].Value = reader[2].ToString();
datakaryawan.Rows[datakaryawan.Rows.Count - 1].Cells["Alamat"].Value = reader[3].ToString();
datakaryawan.Rows[datakaryawan.Rows.Count - 1].Cells["PoB"].Value = reader[4].ToString();
datakaryawan.Rows[datakaryawan.Rows.Count - 1].Cells["DoB"].Value = reader[5].ToString();
datakaryawan.Rows[datakaryawan.Rows.Count - 1].Cells["Telepon"].Value = reader[6].ToString();
datakaryawan.Rows[datakaryawan.Rows.Count - 1].Cells["Divisi"].Value = reader[7].ToString();
datakaryawan.Rows[datakaryawan.Rows.Count - 1].Cells["Aktif"].Value = reader[8].ToString();
datakaryawan.Rows[datakaryawan.Rows.Count - 1].Cells["Password"].Value = reader[9].ToString();
}
connect.Close();
idkaryawantxt.Text = datakaryawan.Rows[0].Cells[0].Value.ToString();
namakaryawantxt.Text = datakaryawan.Rows[0].Cells[1].Value.ToString();
identitastxt.Text = datakaryawan.Rows[0].Cells[2].Value.ToString();
alamattxt.Text = datakaryawan.Rows[0].Cells[3].Value.ToString();
lahirtxt.Text = datakaryawan.Rows[0].Cells[4].Value.ToString();
tgllahirtxt.Text = datakaryawan.Rows[0].Cells[5].Value.ToString();
tlpntxt.Text = datakaryawan.Rows[0].Cells[6].Value.ToString();
divisitxt.Text = datakaryawan.Rows[0].Cells[7].Value.ToString();
aktiftxt.Text = datakaryawan.Rows[0].Cells[8].Value.ToString();
passwordtxt.Text = datakaryawan.Rows[0].Cells[9].Value.ToString();
}
The word PASSWORD is reserved for MS-Access databases.
If you want to use it you need to encapsulate it in square brackets
string q = #"insert into Table1 (Nama,No_Identitas,Alamat,Lahir,Tanggal_Lahir,
Telepon,Divisi,Aktif,[Password]) values (.....)";
said that keep in mind that string concatenation to form a sql command is a bad practice and should be avoided at all costs using a parameterized query.
The worst problem with string concatenation to build sql commands is the possibility of Sql Injection attacks, but also strings that contain single quotes, dates and floating point values are a problem when you need to use their values to build a string concatenated query text.
For example, what happens if one of your text fields contains a single quote typed by your user?. Another syntax error because when you concatenate a string containing a quote you break the required syntax for the command.
So there is no other acceptable way than use a parameterized query
string q = #"insert into Table1 (Nama,No_Identitas,Alamat,Lahir,Tanggal_Lahir,
Telepon,Divisi,Aktif,[Password]) values (?,?,?,?,?,?,?,?,?,?)";
using(OleDbConnection connect = new OleDbConnection(.....))
using(OleDbCommand cmd = new OleDbCommand(q, connect)
{
connect.Open()
cmd.Parameters.AddWithValue("#p1", namakaryawantxt.Text);
... so on for the other 8 parameters
... REMEMBER TO ADD THEM IN THE SAME ORDER OF THE PLACEHOLDERS ...
cmd.ExecuteNonQuery();
}

SQL Table Edit: Add DateTime value in table

I made SQL table editor for add info in some columns. But one column is set to "DateTime" in and application can't write it . Here is the code:
private void button2_Click(object sender, EventArgs e)
{
try
{
string connectionString = #"Data Source=" + textBox4.Text + ";" + "Initial Catalog=" + textBox1.Text + ";" + "User ID=" + textBox2.Text + ";" + "Password=" + textBox3.Text;
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO user_ban (char_id, status, ban_date, ban_hour, ban_end) VALUES (#char_id, #status, DateTime #ban_date, #ban_hour, #ban_end)";
command.Parameters.AddWithValue("#char_id", "1");
command.Parameters.AddWithValue("#status", "1");
command.Parameters.AddWithValue("#ban_date", "1");
command.Parameters.AddWithValue("#ban_hour", "1");
command.Parameters.AddWithValue("#ban_end", "1");
connection.Open();
command.ExecuteNonQuery();
MessageBox.Show("Char Banned");
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
Column 'ban_date' is set to DateTime.
Thank you!
"1" is not a date. Try passing a date to it
command.Parameters.AddWithValue("#ban_date", DateTime.Today);
And remove the DateTime from the command string
command.CommandText = "INSERT INTO user_ban
(char_id, status, ban_date, ban_hour, ban_end)
VALUES
(#char_id, #status, #ban_date, #ban_hour, #ban_end)";
If ban_date column is DateTime, why you want to insert 1 to it? Does not make sense. 1 is not a valid DateTime at all. Change it to a valid DateTime value.
Second, you should not use value type in your VALUES part. Change it from
command.CommandText = "INSERT INTO user_ban (char_id, status, ban_date, ban_hour, ban_end)
VALUES (#char_id, #status, DateTime #ban_date, #ban_hour, #ban_end)";
^^^^^^^^^//delete this
to
command.CommandText = "INSERT INTO user_ban (char_id, status, ban_date, ban_hour, ban_end)
VALUES (#char_id, #status, #ban_date, #ban_hour, #ban_end)";

Categories

Resources