A little noob says HY.
I have a small problem with a homework project in Microsoft Visual Studio 2010.
Also, i work in C#.
I must do a site for selling products and i have an Access database.
So, the problem is this: i wrote code but it seems something is wrong and i don't know what!
When i try to Add a command by site i receive an error:
Data type mismatch in criteria expression.
Code is:
string date = DateTime.Now.ToShortDateString();
string string_baza_de_date = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\BogCs\Documents\Visual Studio 2010\WebSites\WebSite1\App_Data\magazin.mdb";
OleDbConnection ConexiuneSQL = new OleDbConnection(string_baza_de_date);
ConexiuneSQL.Open();
int numar_total_de_produse = CheckBoxList1.Items.Count; // se numara produsele
for (int i = 0; i < numar_total_de_produse; i++) // de la primul articol din CheckBoxList1 pana la ultimul
{
if (CheckBoxList1.Items[i].Selected == true) // daca am selectat un produs
{
// interogarea comenzii:
string interogare_adauga_comanda = "INSERT INTO comanda_finala (ID_comanda, ID_client, ID_produs, produs, tip_produs, data_comanda, pret) VALUES ("
+ TextBox1.Text + ",'" + TextBox2.Text + "',"
+ CheckBoxList1.Items[i].Value + ",'" + CheckBoxList1.Items[i].Text + "', 'Televizoare LED','"
+ data_curenta + "','" + GridView3.Rows[i].Cells[3].Text.ToString() + "');";
OleDbCommand comanda_inserare_comanda = new OleDbCommand(interogare_adauga_comanda, ConexiuneSQL);
comanda_inserare_comanda.ExecuteNonQuery();
}
}
ConexiuneSQL.Close();
GridView3.Visible = false;
Button1.Visible = false;
Button2.Visible = false;
CheckBoxList1.Visible = false;
Label1.Visible = false;
TextBox1.Visible = false;
Label2.Visible = true;
When i press "Add command" gives me that error and i don't know how to solve!
you have to put " ' " before and after textbox1.text
so it would look like this:
string interogare_adauga_comanda = "INSERT INTO comanda_finala (ID_comanda, ID_client, ID_produs, produs, tip_produs, data_comanda, pret) VALUES ('" + TextBox1.Text + "','" + TextBox2.Text + "', " + CheckBoxList1.Items[i].Value + ",'" + CheckBoxList1.Items[i].Text + "', 'Televizoare LED','"+ data_curenta + "','" + GridView3.Rows[i].Cells[3].Text.ToString()+ "');";
Probably the error lies in some of your strings used to build the command.
As usual this is the first obvious reason to use parametrized query.
Let the framework code format your strings according to the rules of the current database.
The most important reason however, is the Sql Injecton problem
So let me change your code in this way to get rid of that ugly string concatenation
string interogare_adauga_comanda = "INSERT INTO comanda_finala (ID_comanda, ID_client, "+
"ID_produs, produs, tip_produs, data_comanda, pret) " +
"VALUES (?,?,?,?,?,?,?)";
OleDbCommand comanda_inserare_comanda = new OleDbCommand(interogare_adauga_comanda, ConexiuneSQL);
comanda_inserare_comanda.Parameters,AddWithValue("#p1",TextBox1.Text );
comanda_inserare_comanda.Parameters,AddWithValue("#p2",TextBox2.Text );
comanda_inserare_comanda.Parameters,AddWithValue("#p3",CheckBoxList1.Items[i].Value );
comanda_inserare_comanda.Parameters,AddWithValue("#p4",CheckBoxList1.Items[i].Text );
comanda_inserare_comanda.Parameters,AddWithValue("#p5","Televizoare LED");
comanda_inserare_comanda.Parameters,AddWithValue("#p6",data_curenta);
comanda_inserare_comanda.Parameters,AddWithValue("#p7",GridView3.Rows[i].Cells[3].Text.ToString());
comanda_inserare_comanda.ExecuteNonQuery();
Also, keep in mind that you should pass the value to the parameters with the correct datatype expected by the database field. For example, if your first field ID_comanda is numeric then the line of the relative parameter should be changed to
comanda_inserare_comanda.Parameters,AddWithValue("#p1",Convert.ToInt32(TextBox1.Text));
and this raises another problem. Did you check if the text in the TextBox1 is really a number?
Related
I am trying to add datatable if the data is not existing before
public async Task saveBetEntity(List<BetEntity> betList)
{
DataTable dt = new DataTable();
// dt.Columns.Add("ItemId");
dt.Columns.Add("Player_no");
dt.Columns.Add("PLAYER_BET_NUMBER");
dt.Columns.Add("BET_PLACED_DATE");
dt.Columns.Add("OVER_1000_SEK");
dt.Columns.Add("EVENT_NAME");
dt.Columns.Add("LEAGUE");
dt.Columns.Add("BET_OFFER_TYPE");
dt.Columns.Add("CRITERIA_NAME");
dt.Columns.Add("IS_LIVE");
dt.Columns.Add("BET_LABEL");
dt.Columns.Add("ODDS");
dt.Columns.Add("BET_OUTCOME");
if (betList != null && betList.Count > 0)
{
foreach (var item in betList)
{
DataRow dr = dt.NewRow();
dr["Player_no"] = item.Player_no;
dr["PLAYER_BET_NUMBER"] = item.PLAYER_BET_NUMBER;
dr["BET_PLACED_DATE"] = item.BET_PLACED_DATE;
dr["OVER_1000_SEK"] = item.OVER_1000_SEK;
dr["EVENT_NAME"] = item.EVENT_NAME;
dr["LEAGUE"] = item.LEAGUE;
dr["BET_OFFER_TYPE"] = item.BET_OFFER_TYPE;
dr["CRITERIA_NAME"] = item.CRITERIA_NAME;
dr["IS_LIVE"] = item.IS_LIVE;
dr["BET_LABEL"] = item.BET_LABEL;
dr["ODDS"] = item.ODDS;
dr["BET_OUTCOME"] = item.BET_OUTCOME;
dt.Rows.Add(dr);
}
for (int i = 0; i < dt.Rows.Count; i++)
{
string InsertQuery = string.Empty;
InsertQuery =
"IF NOT EXISTS (SELECT * FROM BetEntities WHERE Player_no =dt.Rows[i][\"Player_no\"].ToString() BEGIN" +
"INSERT INTO BetEntities " +
"(Player_no, PLAYER_BET_NUMBER, BET_PLACED_DATE, OVER_1000_SEK, EVENT_NAME," +
" LEAGUE, BET_OFFER_TYPE, CRITERIA_NAME, IS_LIVE, BET_LABEL, ODDS, BET_OUTCOME) " +
"VALUES ('" + dt.Rows[i]["Player_no"].ToString() + "','" + dt.Rows[i]["PLAYER_BET_NUMBER"].ToString() + "','" + dt.Rows[i]["BET_PLACED_DATE"].ToString()
+ "','" + dt.Rows[i]["OVER_1000_SEK"].ToString() + "','" + dt.Rows[i]["EVENT_NAME"].ToString() + "','" + dt.Rows[i]["LEAGUE"].ToString() +
"','" + dt.Rows[i]["BET_OFFER_TYPE"].ToString() + "','" + dt.Rows[i]["CRITERIA_NAME"].ToString() + "','" + dt.Rows[i]["IS_LIVE"].ToString() +
"','" + dt.Rows[i]["BET_LABEL"].ToString() + "','" + dt.Rows[i]["ODDS"].ToString() + "','" + dt.Rows[i]["BET_OUTCOME"].ToString() + "')" +
" WHERE NOT EXISTS ( SELECT * FROM BetEntities WHERE Player_no =dt.Rows[i][\"Player_no\"].ToString()" +
" AND PLAYER_BET_NUMBER = dt.Rows[i][\"PLAYER_BET_NUMBER\"].ToString() " +
" AND BET_PLACED_DATE =dt.Rows[i][\"BET_PLACED_DATE\"].ToString()" +
" AND OVER_1000_SEK =dt.Rows[i][\\\"OVER_1000_SEK\\\"].ToString()\"" +
" AND EVENT_NAME =dt.Rows[i][\\\"EVENT_NAME\\\"].ToString()\"" +
" AND LEAGUE =dt.Rows[i][\\\" LEAGUE\\\"].ToString()\"" +
" AND BET_OFFER_TYPE =dt.Rows[i][\\\"BET_OFFER_TYPE\\\"].ToString()\"" +
" AND CRITERIA_NAME =dt.Rows[i][\\\"CRITERIA_NAME\\\"].ToString()\"" +
" AND IS_LIVE =dt.Rows[i][\\\" IS_LIVE\\\"].ToString()\"" +
" AND BET_LABEL =dt.Rows[i][\\\"BET_LABEL\\\"].ToString()\"" +
" AND BET_OUTCOME=dt.Rows[i][\\\" BET_OUTCOME\\\"].ToString()\"" +
");";
using (SqlConnection destinationConnection = new SqlConnection(_configuration.GetConnectionString("ConnectionAPIConeectionString")))
using (var BetEntities = new SqlCommand(InsertQuery, destinationConnection))
{
destinationConnection.Open();
BetEntities.ExecuteNonQuery();
}
}
}
await Task.CompletedTask;
}
The code works fine if I delete
" WHERE NOT EXISTS ( SELECT * FROM BetEntities WHERE Player_no =dt.Rows[i][\"Player_no\"].ToString()" +
" AND PLAYER_BET_NUMBER = dt.Rows[i][\"PLAYER_BET_NUMBER\"].ToString() " +
" AND BET_PLACED_DATE =dt.Rows[i][\"BET_PLACED_DATE\"].ToString()" +
" AND OVER_1000_SEK =dt.Rows[i][\\\"OVER_1000_SEK\\\"].ToString()\"" +
" AND EVENT_NAME =dt.Rows[i][\\\"EVENT_NAME\\\"].ToString()\"" +
" AND LEAGUE =dt.Rows[i][\\\" LEAGUE\\\"].ToString()\"" +
" AND BET_OFFER_TYPE =dt.Rows[i][\\\"BET_OFFER_TYPE\\\"].ToString()\"" +
" AND CRITERIA_NAME =dt.Rows[i][\\\"CRITERIA_NAME\\\"].ToString()\"" +
" AND IS_LIVE =dt.Rows[i][\\\" IS_LIVE\\\"].ToString()\"" +
" AND BET_LABEL =dt.Rows[i][\\\"BET_LABEL\\\"].ToString()\"" +
" AND BET_OUTCOME=dt.Rows[i][\\\" BET_OUTCOME\\\"].ToString()\"" +
I don't want to add the data over and over, that's why I added this code.
You have many errors in your code.
First error is related to not using verbatim string. Without a verbatim string, your SQL Command is a mess and and it is very hard to see the basic errors there that would cause a syntax error on the SQL server side and wouldn't execute at all. You said it works if that "where" didn't exist, but your code is already erroenous without it.
Next there is error from T-SQL point of view if you didn't miss a single quote or double quote and wrote the command string perfectly correct. Your command would conceptually look like:
IF NOT EXISTS ( SELECT * FROM BetEntities WHERE Player_no ... )
BEGIN
INSERT INTO BetEntities
( Player_No, ... ) VALUES ( 1, ... )
WHERE NOT EXISTS (Select ... )
END;
However this is invalid T-SQL syntax. You can't use
... VALUES (...) WHERE
To overcome that limitation, you just need to change the syntax a bit and move that "NOT EXISTS" check to the "IF NOT EXISTS" check at top. That is what you are doing after all.
Third error is the one that you might have passed if you put all those + single and double quotes right in your code and that would be a guaranteed disaster in future if not today. You were lucky, indirectly it didn't work and you are here. As I said in comments, never ever write an SQL command like that concatenating strings and putting user inputs within that. That is because:
It makes your SQL code wide open to bad things, widely known as SQL Injection Attack.
Many users get away ignoring the use parameters saying, thinking it is only for SQL Injection Attacks and their code is never open to a real user input from outside or they think they are sanitizing it with some way (well hackers know ways against sanitization if I do know as one mere coder). However, it doesn't only prevent SQL Injection Attack but also take care of the formatting of input values themselves. For datetimes for example, if you were passing it as a string (don't), then it should be in a specific format in order to be independent of server settings. Or with a string, if the string itself contained quote or double quote (ie: O'Hara, 24" pipe) then it would fail or be interpreted in a very different way, although it was an innocent query.
You decide which one of the above reasons are more important in order to use parameters, but at the end I repeat:
Never ever write an SQL command like that concatenating strings and putting user inputs within that.
(I even have a tendency to write that in capitals:)
Then comes another question, why would you ever need a DataTable in between? Directly use the list itself.
A side note by the way, with a list or DataTable or whatever (like
json, xml, ...), if there are many rows to write, then instead of a
loop, you would surely want to do this with the SqlBulkCopy class or
T-SQL Bulk copy or using JSON, XML ...
OK, having said all these, here is a revised version of your code with parameters and verbatim string. You can see the difference in readability at least:
public async Task saveBetEntity(List<BetEntity> betList)
{
if (betList == null)
{
return;
}
string insertQuery = #"IF NOT EXISTS
(
SELECT *
FROM BetEntities
WHERE Player_no = #Player_no
AND PLAYER_BET_NUMBER = #PLAYER_BET_NUMBER
AND BET_PLACED_DATE = #BET_PLACED_DATE
AND OVER_1000_SEK = #OVER_1000_SEK
AND EVENT_NAME = #EVENT_NAME
AND LEAGUE = #LEAGUE
AND BET_OFFER_TYPE = #BET_OFFER_TYPE
AND CRITERIA_NAME = #CRITERIA_NAME
AND IS_LIVE = #IS_LIVE
AND BET_LABEL = #BET_LABEL
AND BET_OUTCOME = #BET_OUTCOME
)
BEGIN
INSERT INTO BetEntities
(
Player_no, PLAYER_BET_NUMBER, BET_PLACED_DATE,
OVER_1000_SEK, EVENT_NAME, LEAGUE,
BET_OFFER_TYPE, CRITERIA_NAME, IS_LIVE,
BET_LABEL, ODDS,BET_OUTCOME
)
VALUES
(#Player_no, #PLAYER_BET_NUMBER, #BET_PLACED_DATE,
#OVER_1000_SEK, #EVENT_NAME, #LEAGUE,
#BET_OFFER_TYPE, #CRITERIA_NAME, #IS_LIVE,
#BET_LABEL, #ODDS, #BET_OUTCOME);
END;
";
using (SqlConnection destinationConnection = new SqlConnection(_configuration.GetConnectionString("ConnectionAPIConeectionString")))
using (var insertCommand = new SqlCommand(insertQuery, destinationConnection))
{
insertCommand.Parameters.Add("#Player_no", SqlDbType.Int);
insertCommand.Parameters.Add("#PLAYER_BET_NUMBER", SqlDbType.Int);
insertCommand.Parameters.Add("#BET_PLACED_DATE", SqlDbType.DateTime);
insertCommand.Parameters.Add("#OVER_1000_SEK", SqlDbType.Text);
insertCommand.Parameters.Add("#EVENT_NAME", SqlDbType.Text);
insertCommand.Parameters.Add("#LEAGUE", SqlDbType.Text);
insertCommand.Parameters.Add("#BET_OFFER_TYPE", SqlDbType.Text);
insertCommand.Parameters.Add("#CRITERIA_NAME", SqlDbType.Text);
insertCommand.Parameters.Add("#IS_LIVE", SqlDbType.Bit);
insertCommand.Parameters.Add("#BET_LABEL", SqlDbType.Text);
insertCommand.Parameters.Add("#ODDS", SqlDbType.Text);
insertCommand.Parameters.Add("#BET_OUTCOME", SqlDbType.Text);
destinationConnection.Open();
foreach (var item in betList)
{
insertCommand.Parameters["#Player_no"].Value = item.Player_no;
insertCommand.Parameters["#PLAYER_BET_NUMBER"].Value = item.PLAYER_BET_NUMBER;
insertCommand.Parameters["#BET_PLACED_DATE"].Value = item.BET_PLACED_DATE;
insertCommand.Parameters["#OVER_1000_SEK"].Value = item.OVER_1000_SEK;
insertCommand.Parameters["#EVENT_NAME"].Value = item.EVENT_NAME;
insertCommand.Parameters["#LEAGUE"].Value = item.LEAGUE;
insertCommand.Parameters["#BET_OFFER_TYPE"].Value = item.BET_OFFER_TYPE;
insertCommand.Parameters["#CRITERIA_NAME"].Value = item.CRITERIA_NAME;
insertCommand.Parameters["#IS_LIVE"].Value = item.IS_LIVE;
insertCommand.Parameters["#BET_LABEL"].Value = item.BET_LABEL;
insertCommand.Parameters["#ODDS"].Value = item.ODDS;
insertCommand.Parameters["#BET_OUTCOME"].Value = item.BET_OUTCOME;
insertCommand.ExecuteNonQuery();
}
}
await Task.CompletedTask;
}
Note: I made guesses on the real SqlDbTypes. Reality might be different, and your list content might not be checked already (ie: It may contain a string value for something that is DateTime or a number, I skipped checking things like that which you should control with TryParse, if that is a possibility. With proper Lists it shouldn't be).
You will need to do it as you were doing before, otherwise, you are sending a string that SQL does not interpret:
Instead of this:
" WHERE NOT EXISTS ( SELECT * FROM BetEntities WHERE Player_no =dt.Rows[i][\"Player_no\"].ToString()" +
Do this for each value from the datatable:
" WHERE NOT EXISTS ( SELECT * FROM BetEntities WHERE Player_no = " + dt.Rows[i]["Player_no"].ToString() +
For a few week I've been working on this application. One of the users wishes was to save and display images. So I've created this opportunity for the user to insert screenshots. However, when I first send the images to the database and retrieve them again, they can't be decoded into images anymore. (Error: Parameter is not valid.) So I checked whether is was the code or something else. I found out, that after converting the image into byte[], I could revert and display that without any trouble. So the problem lays somewhere between writing to the database and getting it back again. I had a look in the database, and noticed that every image started with 0x, even if there was no image to upload. I read something about some databases might add a header, so I guess that's what creates the problem. But now I need to know how to get rid of that header. And if I get rid of that reader, can I still just use the GetValue() function, or do I really need to use GetBytes()? The reason I didn't go for GetBytes in the first place, is that I need to assign a length in start, but that changes from image to image.
Can anyone tell me how to delete that header if that comes with it? I checked the values of the first few bytes, I hoped if I dropped the first two, they represent the 0x and the problem would be solved, but that's not how it works apparently. After that, I tried to upload a picture to the db and retrieve it again, I noticed the length went from 566 to 1335. The empty picture however, despite that the db says it has 0x in it, has a byte[] with a length of 0.
The object bsk will be send to a part of the code, which writes that to the database:
String command = "INSERT INTO " + db.getTabelbsk() + " VALUES ('" + bsk.getEmailapplicant() + "','" + bsk.getCreation().ToString("MM-dd-yyyy") + "','" + bsk.getCrmQuoteNumber()
+ "','" + bsk.getProjectStage() + "','" + bsk.getRefArticleId() + "','" + bsk.getClassification() + "','" + bsk.getDescription() + "','" +
bsk.getTrackingnumber() + "','" + bsk.getLastModified().ToString("MM-dd-yyyy") + "','" + bsk.getStatus() + "','" + bit + "','" + bsk.getScr() + "','" +
bsk.getBskMail() + "','" + bsk.getEnd12Mail() + "','" + bsk.getEnd3elecMail() + "','" + bsk.getEnd3swMail() + "','" + bsk.getPrmMail() + "','" +
bsk.getRejectMail() + "','" + bsk.getRejectReason() + "','" + bsk.getCommercialDescription() + "','" + bsk.getTechnicalDescription() + "','" +
bsk.getValue() + "','" + bsk.getEndhours() + "', '" + bsk.getLockedBy() + "', '";
command = addImages(command, bsk.getSrcSs()) + "', '" + addImages(command, bsk.getTechnicalDescriptionSs()) + "');";
sqlcommand(con, command);
private String addImages(String command, byte[] ba)
{ //Adds every byte to the command String
foreach (byte b in ba)
{
command += b;
}
return command;
}
public SqlDataReader sqlcommand(SqlConnection con, String s)
{ //Executes the command
try
{
con.Close();
}
catch { }
SqlCommand cmd = new SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = s;
cmd.Connection = con;
try
{
con.Open();
}
catch
{
}
SqlDataReader reader = cmd.ExecuteReader();
return reader;
}
This part is used to retrieve data from the database:
public Bsk returnBsk(Database db, Bsk bsk, SqlConnection con)
{ //This will retrieve the data from the database
String table = db.getTabelbsk();
int trackingnumber = bsk.getTrackingnumber();
String command = "SELECT * FROM " + table + " WHERE trackingNumber = " + trackingnumber;
SqlDataReader reader = sqlcommand(con, command);
reader.Read(); //Filling the object with data
bsk.setEmailapplicant(reader.GetString(0));
bsk.setCreation(reader.GetDateTime(1));
bsk.setCrmQuoteNumber(reader.GetString(2));
bsk.setProjectStage(reader.GetString(3));
bsk.setRefArticleId(reader.GetString(4));
bsk.setClassification(reader.GetString(5));
bsk.setDescription(reader.GetString(6));
bsk.setLastModified(reader.GetDateTime(8));
bsk.setStatus((Bsk.Status)Enum.Parse(typeof(Bsk.Status), reader.GetString(9)));
if (reader.GetBoolean(10) == false)
{
bsk.setComplexity((Bsk.Complexity.Simple));
}
else if (reader.GetBoolean(10) == true)
{
bsk.setComplexity((Bsk.Complexity.Complex));
}
bsk.setScr(reader.GetString(11));
bsk.setBskMail(reader.GetString(12));
bsk.setEnd12Mail(reader.GetString(13));
bsk.setEnd3elecMail(reader.GetString(14));
bsk.setEnd3swMail(reader.GetString(15));
bsk.setPrmMail(reader.GetString(16));
bsk.setRejectMail(reader.GetString(17));
bsk.setRejectReason(reader.GetString(18));
bsk.setCommercialDescription(reader.GetString(19));
bsk.setTechnicalDescription(reader.GetString(20));
bsk.setValue(reader.GetInt32(21));
bsk.setEndhours(reader.GetInt32(22));
bsk.setLockedBy(reader.GetString(23));
if (!Convert.IsDBNull(reader.GetValue(24)))
{
bsk.setSrcSs((byte[])reader.GetValue(24));
}
if (!Convert.IsDBNull(reader.GetValue(25)))
{
bsk.setTechnicalDescriptionSs((byte[])reader.GetValue(25));
}
reader.Close();
con.Close();
return bsk;
}
Image to byte[]:
Image imageSrc = pb_Src.Image;
byte[] arrSrc;
ImageConverter converterSrc = new ImageConverter();
arrSrc = (byte[])converterSrc.ConvertTo(imageSrc, typeof(byte[]));
bsk.setSrcSs(arrSrc);
byte[] to image:
byte[] arrSrc = bsk.getSrcSs();
MemoryStream ms = new MemoryStream(arrSrc);
pb_Src.Image = Image.FromStream(ms); <-- Error message appears here
PS:
I'm aware that How to display image from database in c# is related. However, this question never got answered.
I am getting an error
ERROR [42500] ERROR: 3020 - There was an error when converting the date value "0000-00-48. In the field "salesOrder Transaction Date
The date value I am trying to insert is 4/4/2018.
My code
DateTime JobDate = Wintac_JobDate;
string addSalesOrder = "INSERT INTO SalesOrderLine (CustomerRefListID, TemplateRefListID," +
" SalesOrderLineItemRefListID, SalesOrderLineDesc,SalesOrderLineQuantity, SalesOrderLineRate, " +
"SalesOrderLineSalesTaxCodeRefListID, Memo, SalesOrderLineInventorySiteRefListID, SalesOrderLineInventorySiteLocationRefListID" +
", TxnDate, ShipAddressAddr1, ShipAddressAddr2, ShipAddressAddr3, ShipAddressAddr4, ShipAddressAddr5, FQSaveToCache)" +
"VALUES('" + QBCustomerListID + "','" + templateLID + "', '" + LID + "', '" + Description + "', " + Quantity + ", " + 120 + "," +
" '" + SalesTax + "', '" +Wintac_WipNo+"','"+LaborSite+"','"+LaborSiteLocation+"',"+
"?,'" + shipAdr1+ "','" + shipAdr2 + "','" + shipAdr3 + "','" + shipAdr4 + "','" + shipAdr5 + "'," +
""+ FQSaveToCache + ")";
OdbcCommand sqlcmd2 = new OdbcCommand(addSalesOrder, quickbookscon2);
sqlcmd2.CommandType = CommandType.Text;
sqlcmd2.CommandTimeout = 180;
MessageBox.Show(JobDate.ToShortDateString());
sqlcmd2.Parameters.Add("P7", OdbcType.DateTime).Value = JobDate
if (Quantity != 0)
{
if (sqlcmd2.ExecuteNonQuery() == 1)
{
if(FQSaveToCache == 0)
MessageBox.Show(" added successfully.");
}
}
sqlcmd2.Dispose()
I have tried converting the variable Job Date
Date Time
short date string
long date string
entering the variable directly into the query
Any help would be appreciated.
I think the main problem is on that line;
sqlcmd2.Parameters.Add("P7", OdbcType.DateTime).Value = JobDate.ToLongDateString()
You try to insert string representation on a DateTime typed column. That's quite wrong. You need to directly pass your DateTime value instead of passing it string representation. To learn this as a habit, please read Bad habits to kick : choosing the wrong data type
Other than this, I saw a few problem also in your code:
You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Use using statement to dispose your connection and commmand automatically instead of callind Dispose method manually which you didn't even consider to do in your code.
I'm working on my collage project i have a bill generate form in asp.net c# , my problem is that when i select a last value from database and enter a new data for bill . and then when i save that record that will be store in database and genrate a new index value for dropdown box . so when i select a last value from dropdown i get all clear field in all text boxes.
but right now when i select a last value fromj dropdown then i get a record from last inserted values in textbox .
so please can anyone help me..
thank you in advance.
have a nice day.![enter image description here][1]
here is a screen short of my bill genration.
and i select a trans. no from dropdown.
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
string qry1 = "select trans_id from purchase";
if (qry1 == ddltansid.SelectedValue)
{
string qry2 = "update purchase set bill_no=" + txtbillno.Text + ",date = '" + txtdate.Text + "',comp_name='" + ddlcompname.SelectedValue + "',add1='" + txtadd.Text + "',phno=" + txtbxphno.Text + ",cst=" + txtbxcst.Text + ",add_tax=" + txtbxaddtax.Text + ",discount=" + txtbxdisc.Text + ",sub_total=" + txtbxsubtotal.Text + ",g_total=" + txtbxgtotal.Text + ",net_amt=" + txtbxamt.Text + "";
c.Execute(qry2);
MessageBox.Show("update successfully";
}
else
{
str = "Insert into purchase(bill_no,date,comp_name,add1,phno,cst,add_tax,discount,sub_total,g_total,net_amt) values(" + txtbillno.Text + ",'" + txtdate.Text + "','" + ddlcompname.SelectedItem + "','" + txtadd.Text + "'," + txtbxphno.Text + "," + txtbxcst.Text + ",'" + txtbxaddtax.Text + "'," + txtbxdisc.Text + "," + txtbxsubtotal.Text + "," + txtbxgtotal.Text + "," + txtbxnetamt.Text + "";
c.Execute(str);
MessageBox.Show("insert successfully";
}
str1 = "select medicin_name from pur_tans where name='" + ddlmedicine.SelectedValue + "'";
str2 = "select item_name from stock_master";
a = (String.Compare(str1, str2));
if (a > 0)
{
string str3 = "update stock_master set item_qty = (item_qty + '" + txtbxqty.Text + "') where item_name='" + ddlmedicine.SelectedValue + "'";
c.Execute(str3);
MessageBox.Show("update successfully";
}
else
{
string str4 = "insert into stock_master (item_name,item_qty) values('" + ddlmedicine.SelectedValue + "'," + txtbxqty.Text + "";
c.Execute(str4);
MessageBox.Show("insert successfully";
}
if (ddltansid.SelectedValue == "Add New "
{
ddltansid.SelectedIndex = ddltansid.SelectedIndex - 1;
ddltansid.SelectedValue = ddltansid.SelectedValue + 1;
string last = ddltansid.SelectedValue;
if (IsPostBack == true)
{
ddltansid.SelectedValue = last.ToString();
str = "Insert into purchase(bill_no,date,comp_name,add1,phno,cst,add_tax,discount,sub_total,g_total,net_amt) values('' ,'',' ','','','','','','','','')";
c.Execute(str);
}
}
}
above is code for insert a value in database
Where ddltansid.SelectedValue == "Add New " is executed, i would also set the Text property of your textbox to String.Empty.
A little side node: As far as i understand your code, you put userinput directly into your sql query. You should aviod this since it makes your application wounerable to sql insertion attacks.
e.g. if i write in your textbox:
; drop database --;
i can delet your database.
Have a look at perpared statements in SQL. You might also be able to score some extra points ;)
I am new to programming and is developing a new desktop database applcation in Access, I am trying to insert data into a table. I had two datetime picker and I read the value from it as
jobcodedatabean.PaperRecievedate1 = dtpjobcodedate.Value.Date;
jobcodedatabean.Shipmenentdate = dtpshipmentdate.Value.Date;
and I had passed the databean to a function
public void addaction(JobCodeDataBean jobcodedatabean)
{
MessageBox.Show(jobcodedatabean.Shipmenentdate.ToString());
try
{
OleDbConnection oleDbConnection1 = new System.Data.OleDb.OleDbConnection(connString);
oleDbConnection1.Open();
OleDbCommand oleDbCommand1 = new System.Data.OleDb.OleDbCommand("INSERT INTO jobcodemastertable (jobcode ,customercode,totaltrip,shipmentdate,fromPlace, destination,description ,packagetype ,noofpackage ,contactperson ,jobecodedate ) Values ('" + jobcodedatabean.Jobcode + "', '" + jobcodedatabean.Customercode + "' ," + jobcodedatabean.Totaltrip + "," + jobcodedatabean.Shipmenentdate + " ,'" + jobcodedatabean.Fromplace + "','" + jobcodedatabean.Destination + "','" + jobcodedatabean.Description + "','" + jobcodedatabean.Typeofpackage + "','" + jobcodedatabean.Noofpackages + "','" + jobcodedatabean.Contactperson + "'," + jobcodedatabean.PaperRecievedate1 + ") ", oleDbConnection1);
oleDbCommand1.CommandType = CommandType.Text;
oleDbCommand1.ExecuteNonQuery();
oleDbConnection1.Close();
}
catch (Exception)
{
MessageBox.Show(e);
}
but i am getting the exception at the query
Syntax error (missing operator) in query expression '2/16/2012 12:00:00 AM'.
In access the date fields are in short date format
Please somebody help to sort out my mistake
Incorrect quotations. To avoid these kinds of mistakes, use ordered parameters:
var myCommand = new OleDbCommand(
"INSERT INTO MyTable(someDateField, someTextField, someNumberField) VALUES (?, ?, ?)"
);
myCommand.Parameters.Add(DateTime.Now);
myCommand.Parameters.Add("Some text");
myCommand.Parameters.Add(123);
Using parameters also helps protect against SQL injection attacks. In your example, if one of the strings contained an apostrophe, it would fail unless you correctly converted it to two apostrophes. With parameters these are escaped correctly automatically.
You forgot to enclose dates in quotes:
... ",'" + jobcodedatabean.Shipmenentdate + "' ,'" ...
... "','" + jobcodedatabean.PaperRecievedate1 + "') " ...
Note single quotes around both dates.