Syntax error in INSERT statement (access database) - c#

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();
}

Related

C# Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll

Apologies in advance if I missed an answer to this somewhere but I wasn't quite finding it anywhere. So I'm building an application that scans PDF's of service orders our company gets, parses it, and inserts it into a SQL DB. The problem is at the end of this code. It successfully :
saves the original pdf in the proper folder
scans the pdf and parses it
inserts the correct data into the service order table
grabs PK of service order just created as we need that for the next batch of inserts
Here is where it gets hung up with a Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll
I foreach through all the instruments as there are multiples per Service Order, but it is erroring on this somewhere. to be clear I put a break point on the insert statement and all of the data is good and in the proper format ("string" int)
I feel like its in my connection maybe?
Anyways, thanks in advance for the help.
string filename = Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath("~/PDF/") + filename);
// Now we parse the PDF by creating a new ServiceOrder object and parsing from it.
ServiceOrder so = new ServiceOrder();
// Make sure we load the PDF from the correct path on the server
so.LoadPDF(Server.MapPath("~/PDF/") + filename);
String strConnString = "Data Source=127.0.0.0;Initial Catalog=SOMECATALOG;User ID=SOMEUSER;Password=SOMEPASSWORD";
// Insert Into Service Orders Table
string defaultdate = DateTime.Now.ToString("yyyy-MM-dd");
String strQuery = "insert into TServiceOrders (strServiceOrderNo, intStatusCodeID, strCustomerName, strCustomerNo, strCustomerAddress1, strCustomerAddress2, strCustomerAddress3, intRepID, strServiceDescription, strServiceRequestDate, strServiceOrderDate, strNotes) values ('"
+ so.ServiceOrderNumber.ToString() + "', 2, '"
+ so.CustomerContactName.ToString() + "', '"
+ so.CustomerNumber.ToString() + "', '"
+ so.CustomerContactAddress1.ToString() + "', '"
+ so.CustomerContactAddress2.ToString() + "', '"
+ so.CustomerContactAddress3.ToString() + "', 1, '', '"
+ defaultdate + "', '" + defaultdate + "', '')";
SqlConnection conn = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand(strQuery, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
// Grabbing latest primary key od service order just added for next instrument inserts
int lastid = 999999;
String strPKquery = "select top 1 intServiceOrderID from TServiceOrders order by intServiceOrderID desc";
SqlDataReader rdr = null;
SqlConnection conn2 = new SqlConnection(strConnString);
SqlCommand cmd2 = new SqlCommand(strPKquery, conn2);
try
{
conn2.Open();
rdr = cmd2.ExecuteReader();
while (rdr.Read())
{
lastid = (int)rdr["intServiceOrderID"];
}
}
finally
{
if (rdr != null)
{
rdr.Close();
}
if (conn2 != null)
{
conn2.Close();
}
}
// Insert Into Service Instruments Tables
SqlConnection conn3 = new SqlConnection(strConnString);
conn3.Open();
foreach (ServiceInstrument sin in so.ServiceInstruments)
{
string sim = "";
sim = sin.ServiceInstrumentModel;
if (String.IsNullOrEmpty(sim))
{
sim = "";
}
else
{
sim = sin.ServiceInstrumentModel.ToString();
}
string sid = "";
sid = sin.ServiceInstrumentDescription;
if (String.IsNullOrEmpty(sid))
{
sid = "";
}
else
{
sid = sin.ServiceInstrumentDescription.ToString();
}
string sis = "";
sis = sin.ServiceInstrumentSerial;
if (String.IsNullOrEmpty(sis))
{
sis = "";
}
else
{
sis = sin.ServiceInstrumentSerial.ToString();
}
string sih = "";
sih = sin.ServiceInstrumentHandle;
if (String.IsNullOrEmpty(sih))
{
sih = "";
}
else
{
sih = sin.ServiceInstrumentHandle.ToString();
}
string sip = "";
sip = sin.ServiceInstrumentParentAsset;
if (String.IsNullOrEmpty(sip))
{
sip = "";
}
else
{
sip = sin.ServiceInstrumentParentAsset.ToString();
}
String strQuery3 = "insert into TServiceInstruments values ('" + sim.ToString() + "', '" + sid.ToString() + "', '" + sis.ToString() + "', '" + sih.ToString() + "', " + sip.ToString() + ", " + lastid + ")";
SqlCommand cmd3 = new SqlCommand(strQuery3, conn3);
cmd3.ExecuteNonQuery();
}
conn3.Close();
When writing insert statements you should always specify the column names. This will protect the code from changes in the order of the columns in the table schema.
You are not using parameters in your sql statements, this leaves your code vulnerable to Sql Injection.
You should use using statements around your SqlConnection instances to ensure they are closed even when an Exception occurs.
Your logic is very difficult to follow, split your code until methods with meaningful names instead of having 1 "God" method that does everything.
If you follow those guidelines the problem will most likely solve itself in your refactoring.
Update Code Fragment
Note that you should always specify the correct types for your columns and the length if applicable. Also pass the actual value and never the string value.
const String strQuery3 = "INSERT INTO TServiceInstruments (sim, sid, sis, sih, sip, lid) VALUES (#sim, #sid, #sis, #sih, #sip, #lid)";
using(var conection = new SqlConnection(strConnString))
using(SqlCommand command = new SqlCommand(strQuery3, connection))
{
command.Parameters.Add(new SqlParameter("#sim", SqlDbType.VarChar, 200){Value = sim});
command.Parameters.Add(new SqlParameter("#sid", SqlDbType.VarChar, 200){Value = sid});
command.Parameters.Add(new SqlParameter("#sis", SqlDbType.VarChar, 200){Value = sis});
command.Parameters.Add(new SqlParameter("#sih", SqlDbType.VarChar, 200){Value = sih});
command.Parameters.Add(new SqlParameter("#sip", SqlDbType.Int){Value = sip});
command.Parameters.Add(new SqlParameter("#lid", SqlDbType.Int){Value = lid});
connection.Open();
command.ExecuteNonQuery();
}
Final note: You really need to learn how to read Exceptions and this includes the Stack Trace which points directly to the line in the call stack where the Exception originated. If you can understand this then debugging becomes much easier.
Maybe this doesn't deserve to be an answer, but I'm trying to build some reputation, so here goes :).
I suspect that your error lies in the "insert into TServiceInstruments ..." statement. Namely, you are giving the table more (or less) columns. As a good practice, always specify the columns, like this:
insert into TServiceInstruments (column1, column2, column3)
values (1, 2, 3)

Slow performance importing MS Access database into SQL Server

I have a problem with importing items from an MS Access .mdb database file into SQL Server. I wrote a C# application in practice database that extrapolates the data in a .mdb database and places them in a table in a SQL Server database.
My problem is that the .mdb database contains about 300,000 articles which are to be inserted with all of the controls inside the SQL Server database. The .mdb file is selected by the user.
How can I speed up the import of the articles?
This is my C# code:
dbConn = new OleDbConnection(#"Provider = Microsoft.Jet.OLEDB.4.0; Data Source=" + dialog.FileName + "; Persist Security Info = False; Jet OLEDB:Database Password = " + textBoxPwdComet.Text + "; Mode = Share Deny None");
// SqlConnection conn2 = db.apriconnessione();
try
{
string query = "SELECT CODMARCA,CODART,DESCR,UM,PRZNETTO,PRZCASA,DATAAGG FROM ARTICOLI";
string querycontalinee = "SELECT count(*) from ARTICOLI";
OleDbCommand command = new OleDbCommand(query, dbConn);
OleDbCommand commandcontalinee = new OleDbCommand(querycontalinee, dbConn);
dbConn.Open();
int linee = (int)commandcontalinee.ExecuteScalar();
OleDbDataReader reader = command.ExecuteReader();
Articolo a;
labelstatoaggiornamento.Show();
progressBarstatoaggiornamento.Show();
progressBarstatoaggiornamento.Style = ProgressBarStyle.Continuous;
progressBarstatoaggiornamento.Minimum = 0;
progressBarstatoaggiornamento.Maximum = linee;
progressBarstatoaggiornamento.Step = 1;
SqlConnection conn = db.apriconnessione();
while (reader.Read())
{
String CodMarca = "" + reader.GetValue(0).ToString();
String CodArt = "" + reader.GetValue(1).ToString().Replace("'", ""); ;
String Fornitore = "COMET";
String Descrizione = "" + reader.GetValue(2).ToString();
String UM = "" + reader.GetValue(3).ToString();
String PrezzoNetto = "" + reader.GetValue(4).ToString();
String PrezzoCasa = "" + reader.GetValue(5).ToString();
DateTime DataAggiornamento = DateTime.Now;
decimal Prezzo = Decimal.Parse(PrezzoNetto, System.Globalization.NumberStyles.Any);
decimal PrezzoListino = Decimal.Parse(PrezzoCasa, System.Globalization.NumberStyles.Any);
a = new Articolo(CodArt, CodMarca);
a.db = db;
if (a.ControlloDisponibilitàCOMET() == true)
{
string queryAggiornamento = "Update Articolo Set Descrizione='" + Descrizione + "', UM='" + UM + "', Prezzo='" + Prezzo + "',PrezzoListino='" + PrezzoListino + "',DataAggiornamento='" + DataAggiornamento + "',Stato='Aggiornamentoincorso' Where CodMarca = '" + CodMarca + "' AND CodArt = '" + CodArt + "' AND Importato = 'COMET' and Fornitore='COMET' ";
SqlCommand commaggiorna = new SqlCommand(queryAggiornamento, conn);
try
{
commaggiorna.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(" " + ex);
}
}
else
{
string query2 = "INSERT INTO Articolo (CodMarca, CodArt, Fornitore, Importato, Descrizione, UM, Prezzo, PrezzoListino, Stato) VALUES (#CodMarca, #CodArt, #Fornitore, #Importato, #Descrizione, #UM, #Prezzo, #PrezzoListino, #Stato)";
SqlCommand myCommand = new SqlCommand(query2, conn);
myCommand.Parameters.AddWithValue("#CodMarca", CodMarca);
myCommand.Parameters.AddWithValue("#CodArt", CodArt);
myCommand.Parameters.AddWithValue("#Fornitore", Fornitore);
myCommand.Parameters.AddWithValue("#Importato", Fornitore);
myCommand.Parameters.AddWithValue("#Descrizione", Descrizione);
myCommand.Parameters.AddWithValue("#UM", UM);
decimal PrezzoNetto2 = Decimal.Parse(PrezzoNetto, System.Globalization.NumberStyles.Any);
myCommand.Parameters.AddWithValue("#Prezzo", PrezzoNetto2);
decimal PrezzoCasa2 = Decimal.Parse(PrezzoCasa, System.Globalization.NumberStyles.Any);
myCommand.Parameters.AddWithValue("#PrezzoListino", PrezzoCasa2);
DateTime dt = Convert.ToDateTime(DataAggiornamento);
myCommand.Parameters.AddWithValue("#Stato", "Aggiornamentoincorso");
myCommand.ExecuteNonQuery();
}
progressBarstatoaggiornamento.PerformStep();
int percent = (int)(((double)progressBarstatoaggiornamento.Value / (double)progressBarstatoaggiornamento.Maximum) * 100);
progressBarstatoaggiornamento.CreateGraphics().DrawString(percent.ToString() + "%", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(progressBarstatoaggiornamento.Width / 2 - 10, progressBarstatoaggiornamento.Height / 2 - 7));
}
string queryNonDisponibili = "Update Articolo Set Stato='Nondisponibile' where Stato!='Aggiornamentoincorso' AND Fornitore='COMET' AND Importato='COMET'";
string queryNonDisponibili2 = "Update Articolo Set Stato='Disponibile' where Stato='Aggiornamentoincorso' AND Fornitore='COMET' AND Importato='COMET'";
SqlCommand comm = new SqlCommand(queryNonDisponibili, conn);
SqlCommand comm2 = new SqlCommand(queryNonDisponibili2, conn);
comm.ExecuteNonQuery();
comm2.ExecuteNonQuery();
Console.WriteLine("\n Passaggio Completato");
conn.Close();
db.chiudiconnessione();
dbConn.Close();
}
catch (Exception ex)
{
MessageBox.Show("La password è errata oppure " + ex);
}
Consider using SqlBulkCopy. Since you are running sql queries I would suggest you'd work server side as much as possible. Create a temp table in Sql Server, add all records to a datatable or array of datarows and use SqlBulkCopy to import. I think that is the fastest way to move all records to Sql Server.
From there you can synchronize the two tables in Sql Server with only a few queries.
I would use SqlBulkCopy ...
dbConn = new OleDbConnection(#"Provider = Microsoft.Jet.OLEDB.4.0; Data Source=" + dialog.FileName + "; Persist Security Info = False; Jet OLEDB:Database Password = " + textBoxPwdComet.Text + "; Mode = Share Deny None");
SqlConnection conn2 = db.apriconnessione();
string query = "SELECT CODMARCA,CODART,DESCR,UM,PRZNETTO,PRZCASA,DATAAGG FROM ARTICOLI";
OleDbDataAdapter da = new OleDbDataAdapter(query,dbConn);
DataTable dt = new DataTable();
da.Fill(dt);
conn2.Open();
SqlBulkCopy bulk = new SqlBulkCopy(conn2);
bulk.DestinationTableName = "ARTICOLI";
bulk.WriteToServer(dt);
conn2.close();

getting a error oledbexception was unhandled Additional information: No value given for one or more required parameters

I am getting this error while trying to select data from a database and I am lost on how to fix it. My query works in my database but I am not sure what is happening
randomget = "SELECT top 1 id, Department, Team, Process, SubProcess, SubTask, LastUpdatedBy from workload where stepstatus = 'complete' and agent is null or agent = 0 ";
OleDbConnection MyConn = new OleDbConnection();
MyConn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=.......;Persist Security Info=False";;
MyConn.Open();
OleDbCommand cmd = MyConn.CreateCommand();
cmd.CommandText = randomget;
OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
int id = 0;
while (reader.Read())
{
id = int.Parse(reader[0].ToString());
textBox8.Text = reader[6].ToString();
textBox5.Text = reader[1].ToString();
textBox6.Text = reader[2].ToString();
textBox7.Text = reader[3].ToString();
textBox9.Text = reader[4].ToString();
textBox11.Text = reader[5].ToString();
break;
}
// input table name here
textBox2.Text = agentsrf.ToString();
string sqlupdate = "Update workload set agent = '" + agent + "', where ID = " + id + " ' ";
}
public OleDbConnection connection { get; set; }
You have one stray , after set agent = '" + agent + "' just remove it and then it works fine. Also you should use parameterized queries because this kind of string concatenations are open for SQL Injection:
string sqlupdate = "Update workload set agent = #agent where ID = #id ";
cmd.Parameters.AddWithValue("#agent", agent );
cmd.Parameters.AddWithValue("#id", id);
I solved it. One of my field names had a space in it, which I did not spot.

Parameters supplied for object which is not a function. If the parameters are intended as a table hint, a WITH keyword is required

I'm running Windows 7 and II7 and SQL server 2008 R2 . I have an aspx program and when I try to run it I get the following error
Parameters supplied for object 'users' which is not a function. If
the parameters are intended as a table hint, a WITH keyword is
required.
What I've coded is this :
public ArrayList GetGoodsList(string type, string goodsType, string user, string payType, bool flag)
{
conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["Conn"].ToString());
DataSet ds = new DataSet();
sSql = "select count(*) from users('" + type + "','" + goodsType + "','" + user + "','" + payType + "')";
if (flag == true)
{
sSql += "where IsCommend = 1";
}
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = sSql;
conn.Open();
int maxRow = Int32.Parse(cmd.ExecuteScalar().ToString());
sSql = "select * from users('" + type + "','" + goodsType + "','" + user + "','" + payType + "')";
if (flag == true)
{
sSql += "where IsCommend = 1";
}
cmd.CommandText = sSql;
SqlDataReader reader = cmd.ExecuteReader();
ArrayList gInfos = new ArrayList();
GoodsInfo gInfo;
for (int i = 0; i < maxRow; i++)
{
if (reader.Read())
{
gInfo = new GoodsInfo();
gInfo.G_ID = Int32.Parse(reader["G_ID"].ToString());
gInfo.G_Name = reader["G_Name"].ToString();
gInfo.Type = reader["Type"].ToString();
gInfo.GoodsType = reader["GoodsType"].ToString();
gInfos.Add(gInfo);
}
}
conn.Close();
return gInfos;
}
Any idea? Thanks!
Without giving away the answer, your issue in in your SELECT statement, sSql = ...
It's not the correct SQL syntax.
Have a read of this wikipedia article on the SELECT statement.

How to achieve a search for a certain year & amount using C#

Here is a small demo of a SQL database, where one can add, update delete members from a SQL server.
There are two tables in a single SQL Server DB, one is “members” second is “overview”.
In members there is distinct ID column and members personal info like name, address telephone etc.
In overview there are only three columns which are dID, year & amount.
There is one single windows form, language is c# and project is built in Visual Studio 2010, and of course data base in SQL Server 2010.
The windows form has a “reset, insert, update & delete” buttons.
There is one more button besides the dID text box where a distinct ID can be inserted and after clicking Search button the last entry made about the member shows by filling all the text boxes where name address telephone appear. This serves the function that member full info can be seen and changes can be made or can be removed from dB.
There are two text boxes in particular, which are Year & Amount, which shows that the member has paid a certain amount for the certain year.
But as I mentioned in the text boxes you can only see the last entry made. What function I want to achieve is that after inserting dID of person x I could only in the year text box able to insert lets say any previous year and the press search which should like normally fill all the text boxes with info, and in the amount text box should show me the entry from the dB that according to the year I entered how much amount is there or there is nothing which means that may be member has not paid for a certain year.
I need help in achieving this logic programmatically therefore I would like to request assistance.
The present program is as follows :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SQLDatabase
{
public partial class SQLDBDisplay : Form
{
SqlConnection con = new SqlConnection("Data Source=JG-PC\\SQLEXPRESS;Initial Catalog=TEST;Integrated Security=True");
public SQLDBDisplay()
{
InitializeComponent();
}
SqlDataAdapter da;
DataSet ds = new DataSet();
private void btnSearch_Click(object sender, EventArgs e)
{
SqlDataReader reader;
SqlCommand cmd = new SqlCommand();
try
{
string sql = "SELECT * FROM members where dID = '" + txtdID.Text + "' ";
txtYear.Text = sql;
cmd.Connection = con;
cmd.CommandText = sql;
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
txtID.Text = reader["ID"].ToString();
txtName.Text = reader["Name"].ToString();
txtAddress.Text = reader["Address"].ToString();
txtMobile.Text = reader["Mobile"].ToString();
txtEmail.Text = reader["Email"].ToString();
txtdID.Text = reader["dID"].ToString();
}
con.Close();
sql = "SELECT * FROM Overview where dID = '" + txtdID.Text + "' ";
txtYear.Text = txtYear.Text + " : " + sql;
cmd.Connection = con;
cmd.CommandText = sql;
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
txtYear.Text = reader["Year"].ToString();
txtAmount.Text = reader["Amount"].ToString();
txtdID.Text = reader["dID"].ToString();
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void btnReset_Click(object sender, EventArgs e)
{
txtdID.Text = ""; txtName.Text = ""; txtAddress.Text = "";
txtMobile.Text = ""; txtEmail.Text = ""; txtYear.Text = "";
txtAmount.Text = "";
}
private void btnInsert_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
string Sql = "INSERT INTO members (dID, Name, Address, Email, Mobile) VALUES ( '" + txtdID.Text+ "','" + txtName.Text + "','"
+ txtAddress.Text + "', '" + txtEmail.Text + "', '" + txtMobile.Text + "')";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "INSERT INTO Overview (dID, Year, Amount) VALUES ('"+ txtdID.Text +"' ,'" + txtYear.Text + "','" + txtAmount.Text +
"')";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Inserted Scuessfully!!!");
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand();
string Sql = "Update members set Name = '" + txtName.Text + "', Address = '" + txtAddress.Text + "', Email = '" +
txtEmail.Text + "', Mobile = '" + txtMobile.Text + "' WHERE dID = '"
+ txtdID.Text + "'";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "Update overview set Year = '" + txtYear.Text + "', Amount = '" + txtAmount.Text + "' WHERE dID = '"+ txtdID.Text+"'";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Data Scuessfully Updated");
con.Close();
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "DELETE FROM members WHERE dID = '"+ txtdID.Text +"'";
con.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = "DELETE FROM overview WHERE dID = '" + txtdID.Text + "'";
cmd.ExecuteNonQuery();
da = new SqlDataAdapter(cmd);
MessageBox.Show("Record Scuessfully Deleted !");
con.Close();
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
}
private void btnClose_Click(object sender, EventArgs e)
{
Application.Exit();
}
} }
To add a solution to the comments people have made regarding parameters and sql injection, i tend to use the code below when connecting to any database.
using(SqlConnection connection = new SqlConnection("YOUR CONNECTION STRING"))
{
try
{
using(SqlCommand command = new SqlCommand())
{
command.CommandText = "SELECT * FROM members where dID = #MyId";
command.Connection = connection;
// Set the SqlDbType to your corresponding type
command.Parameters.Add("#MyId", SqlDbType.VarChar).Value = txtdID.Text;
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
txtID.Text = reader["ID"].ToString();
txtName.Text = reader["Name"].ToString();
txtAddress.Text = reader["Address"].ToString();
txtMobile.Text = reader["Mobile"].ToString();
txtEmail.Text = reader["Email"].ToString();
txtdID.Text = reader["dID"].ToString();
}
}
}
finally
{
connection.Close();
}
}
You need to group your SELECT on the Amount column. A simple answer to your question would be to modify your second select query like this:
sql = "SELECT Year, dID, SUM(Amount) as Amount FROM Overview where dID = '" + txtdID.Text + "' AND Year = " + txtYear.Text + "GROUP BY amount";
Probably, you would like to use the txtYear.Text value for an SQL parameter, so:
txtYear.Text = sql;
and
txtYear.Text = txtYear.Text + " : " + sql;
don't make too much sense in your code.
Of course, this is not the correct way, as it is prone to SQL Injection. I would recommend you to use SQL Stored Procedures, which are definitely safer regarding SQL Injection.
Another improvement to the code quality would be that you should use using statements to enclose the SQLConnection, SQLCommand and SQLDataReader objects initializations.

Categories

Resources