Can't add particular values to the database - sql

So I'm currently having a problem where I can't seem to add values to my sql-database. I'm constantly getting sql error 104. Saying that some tokens are unknown.
try{
//The part below gets the employee-ID and the names of the skill I want to add to him/her.
String valdAnstalld = jComboBoxUppKompVal.getSelectedItem().toString();
String nyKomp = jComboBoxUppKID.getSelectedItem().toString();
String nyP = jComboBoxUppPF.getSelectedItem().toString();
String nyNiva = jComboBoxUppNiva.getSelectedItem().toString();
//This part takes the name of the skill, and gets its ID-number.
String KompID = "select kid from kompetensdoman where benamning = '" + nyKomp + "'";
String PlattID = "select pid from plattform where benamning = '" + nyP + "'";
//And finally this part is supposed to insert the ID-numbers into the "has_competance" table.
String sqlUppKomp = "insert into har_kompetens VALUES " + "(" + valdAnstalld + ", '"
+ KompID + "', '" + PlattID + "', '" + nyNiva + "' where aid = '" + valdAnstalld + "')";
idb.insert(sqlUppKomp);
JOptionPane.showMessageDialog(null, "Tillagd!");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
uppdateraKomp();

Related

System.Data.OleDb.OleDbException: 'Data type mismatch in criteria expression.' Grid view update

I am working on a grid view update but System.Data.OleDb.OleDbException: 'Data type mismatch in criteria expression error. Please someone help.
protected void ResultGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtFName2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtFName");
TextBox txtDate2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtSM");
TextBox txtCaseType2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtCaseType");
TextBox txtFileno2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtFileno");
TextBox txtCustName2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtCustName");
TextBox txtAddress2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtCustName");
TextBox txtConno2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtConno");
TextBox txtPlotarea2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtPlotarea");
TextBox txtPlotRate2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtPlotRate");
TextBox txtconstarea2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtconstarea");
TextBox txtConstFloor2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtConstFloor");
TextBox txtconstrate2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtconstrate");
TextBox txtPlotvalue2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtPlotvalue");
TextBox txtconstvalue2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtconstvalue");
TextBox txttotalvalue2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txttotalvalue");
TextBox txtRemarks2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtRemarks");
**TextBox txtDatee2 = (TextBox)ResultGridView.Rows[e.RowIndex].FindControl("txtDate2");**
string da = txtDatee2.Text.ToString();
DateTime dt =
DateTime.ParseExact(da, "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
string dateshort = dt.ToShortDateString();
string ID = ResultGridView.DataKeys[e.RowIndex].Values[0].ToString();
cmd.Connection = conn;
cmd.CommandText = "UPDATE Final SET Finance ='" + txtFName2.Text + "' ,SM ='" + txtDate2.Text + "',Case_Type ='" + txtCaseType2.Text + "',File_no ='" + txtFileno2.Text + "',Cust_Name ='" + txtCustName2.Text + "' ,Address ='" + txtAddress2.Text + "',Con_no ='" + txtConno2.Text + "' ,Plot_area ='" + txtPlotarea2.Text + "' ,Plot_Rate ='" + txtPlotRate2.Text + "' ,const_area ='" + txtconstarea2.Text + "' ,Const_Floor ='" + txtConstFloor2.Text + "' ,const_rate ='" + txtconstrate2.Text + "' ,Plot_value ='" + txtPlotvalue2.Text + "' ,const_value ='" + txtConno2.Text + "' ,total_value ='" + txttotalvalue2.Text + "' ,Remarks ='" + txtRemarks2.Text + "'**,Date2 = '"+ dateshort +"'** WHERE ID=" + ID + "";
conn.Open();
cmd.ExecuteNonQuery();
ResultGridView.EditIndex = -1;
FillVendorGrid();
conn.Close();
}
At least, first text expressions for date values should be formatted as to the ISO sequence:
string dateshort = dt.ToString("yyyy'/'MM'/'dd");
second, in Access, these must be wrapped in octothorpes:
"', Date2 = #" + dateshort + "# WHERE ID="
This must be modified for other datetime fields as well.
Or, do your self a big favour and turn to call a parameterised query.

How to avoid every time initialization when value have greater than 0

I have a method that inserts a new record after checking whether it already exists or not.
Here is my method:
protected void btn_save_Click(object sender, EventArgs e)
{
string MobileNo = "";
string replaceValue = txt_mobile.Text.Replace(Environment.NewLine, "$");
string[] values = replaceValue.Split('$');
int uCnt = 0;
int sCnt = 0;
foreach (string item in values)
{
SaveRecord(item.Trim(),out MobileNo,out uCnt,out sCnt);
}
txt_mobile.Text = string.Empty;
if(uCnt > 0)
{
ClientScript.RegisterStartupScript(this.GetType(), "BulkSMS System", "alert('Mobile No(s) : "+MobileNo.TrimEnd(',')+" Already Exist');", true);
}
if(sCnt > 0)
{
ClientScript.RegisterStartupScript(this.GetType(), "BulkSMS System", "alert('" + sCnt + " Record(s) Inserted Successfully');", true);
}
Get_Data();
}
public void SaveRecord(string value, out string MobileNo, out int uCnt, out int sCnt)
{
uCnt = 0; //every time initialized to 0
sCnt = 0; //every time initialized to 0
MobileNo = "";
try
{
DataTable dt = new DataTable();
var dot = Regex.Match(value, #"\+?[0-9]{10}");
if (dot.Success)
{
string str = "SELECT TOP 1 [ID],[MobileNo] FROM[dbo].[whitelistdata]";
str += " WHERE [UserID] = '" + Convert.ToInt32(ddl_users.SelectedValue.ToString()) + "' AND [SenderId] = '" + Convert.ToInt32(ddl_senders.SelectedValue.ToString()) + "' AND [MobileNo] = '" + value + "'";
dt = obj.Get_Data_Table_From_Str(str);
if (dt.Rows.Count > 0)
{
uCnt++;
MobileNo += value + ",";
}
else
{
string str1 = "INSERT INTO [dbo].[whitelistdata]([UserID],[SenderId],[KeywordID],[MobileNo])";
str1 += "VALUES (" + Convert.ToInt32(ddl_users.SelectedValue.ToString()) + "," + Convert.ToInt32(ddl_senders.SelectedValue.ToString()) + ",1," + value + ")";
obj.Execute_Query(str1);
sCnt++;
}
}
}
catch (Exception ex)
{
CommonLogic.SendMailOnError(ex);
ClientScript.RegisterStartupScript(this.GetType(), "BulkSMS System", "alert('" + ex.Message.ToString() + "');", true);
}
}
The problem is every time it's set to 0 when method has been called I want to prevent them when previous value is greater than 0.
Please help me guys..
Please first identify which combination check-in database.
if UserID AND SenderId combination Match Then
string str = "SELECT TOP 1 [ID],[MobileNo] FROM[dbo].[whitelistdata]";
str += " WHERE [UserID] = '" + Convert.ToInt32(ddl_users.SelectedValue.ToString()) + "' AND [SenderId] = '" + Convert.ToInt32(ddl_senders.SelectedValue.ToString()) + "'";
if check the only UserID Match Then
string str = "SELECT TOP 1 [ID],[MobileNo] FROM[dbo].[whitelistdata]";
str += " WHERE [UserID] = '" +
Convert.ToInt32(ddl_users.SelectedValue.ToString()) +"'";
if UserID OR SenderId combination Match Then
string str = "SELECT TOP 1 [ID],[MobileNo] FROM[dbo].[whitelistdata]";
str += " WHERE [UserID] = '" + Convert.ToInt32(ddl_users.SelectedValue.ToString()) + "' OR [SenderId] = '" + Convert.ToInt32(ddl_senders.SelectedValue.ToString()) + "'";
if UserID AND SenderId AND MobileNo combination Match Then
string str = "SELECT TOP 1 [ID],[MobileNo] FROM[dbo].[whitelistdata]";
str += " WHERE [UserID] = '" + Convert.ToInt32(ddl_users.SelectedValue.ToString()) + "' AND [SenderId] = '" + Convert.ToInt32(ddl_senders.SelectedValue.ToString()) + "' AND [MobileNo] = '" + value + "'";
You need to use ref rather than out if you want to keep this design1. That means that the method can assume that the variables are already initialised and you're not forced to re-initialise them within the method:
public void SaveRecord(string value,out string MobileNo,ref int uCnt,ref int sCnt)
{
//uCnt = 0; //initialized by caller
//sCnt = 0; //initialized by caller
MobileNo = ""; //?
....
And at the call site:
SaveRecord(item.Trim(),out MobileNo,ref uCnt,ref sCnt);
You'll also want to do something about MobileNo too if you expect that to accumulate values rather than be over-written each time through the loop. Maybe make it a StringBuilder instead that you just pass normally (no ref or out) and let the SaveRecord method append to. out is definitely wrong for it.
1Many people would frown at a method that clearly wants to return values being declared void and making all returns via ref/out.
Something like:
public bool SaveRecord(string value)
{
...
Returning true for a new record, false for an existing record. I'd probably take out the exception handling from there and let the exception propagate higher before it's handled. Then the call site would be:
if(SaveRecord(item.Trim()))
{
sCnt++;
}
else
{
uCnt++;
MobileNo += item.Trim + ","
}

MS SQL - Parameterized Query with Dynamic Number of Parameters

Right now I am using the following code to generate the WHERE clause in my query. I have a parameter for the search column (searchColumn) plus another parameter from a checked listbox that I use.
If no item is checked there is no WHERE clause at all.
Is it possible to put this into a parameterized query? For the second part there's most likely a way like searchColumn NOT IN ( ... ) where ... ist the data from an array. Though I am not sure how to handle the case when there's nothing checked at all.
Any thoughts or links on this?
strWhereClause = "";
foreach (object objSelected in clbxFilter.CheckedItems)
{
string strSearch = clbxFilter.GetItemText(objSelected);
if (strWhereClause.Length == 0)
{
strWhereClause += "WHERE (" + searchColumn + " = '" + strSearch + "' "
+ "OR " + searchColumn + " = '" + strSearch + "') ";
}
else
{
strWhereClause += "OR (" searchColumn " = '" + strSearch + "' "
+ "OR " + searchColumn + " = '" + strSearch + "') ";
}
}
It sounds like you're just trying to dynamically build a parameterized query string using C#. You're halfway there with your code - my example below builds up a dictionary with paramter names and parameter values, which you can then use to create SqlParamters. One thing I'm not 100% sure about is where searchColumn is coming from - is this generated from user input? That could be dangerous, and parameterizing that would require using some dynamic SQL and probably some validation on your part.
strWhereClause = "";
Dictionary<string, string> sqlParams = new Dictionary<string, string>();
int i = 1;
string paramName= "#p" + i.ToString(); // first iteration: "#p1"
foreach (object objSelected in clbxFilter.CheckedItems)
{
string strSearch = clbxFilter.GetItemText(objSelected);
if (strWhereClause.Length == 0)
{
strWhereClause += "WHERE (thisyear." + strKB + " = #p1 OR " + searchColumn + " = #p1) ";
sqlParams.Add(paramName, strSearch);
i = 2;
}
else
{
paramName = "#p" + i.ToString(); // "#p2", "#p3", etc.
strWhereClause += "OR (" searchColumn " = " + paramName + " "OR " + searchColumn + " = " + paramName + ") ";
sqlParams.Add(paramName, strSearch);
i++;
}
}
Then, when parameterizing your query, just loop through your dictionary.
if (sqlParams.Count != 0 && strWhereclause.Length != 0)
{
foreach(KeyValuePair<string, string> kvp in sqlParams)
{
command.Parameters.Add(new SqlParamter(kvp.Name, SqlDbType.VarChar) { Value = kvp.Value; });
}
}
For reference only:
string strWhereClause;
string searchColumn;
string strKB;
SqlCommand cmd = new SqlCommand();
private void button1_Click(object sender, EventArgs e)
{
strWhereClause = "";
int ParmCount = 0;
foreach (object objSelected in clbxFilter.CheckedItems)
{
string strSearch = clbxFilter.GetItemText(objSelected);
ParmCount += 1;
string strParamName = "#Param" + ParmCount.ToString(); //Param1→ParamN
cmd.Parameters.Add(strParamName, SqlDbType.NVarChar);
cmd.Parameters[strParamName].Value = strSearch;
if (strWhereClause.Length == 0)
{
strWhereClause += "WHERE (thisyear." + strKB + " = " + strParamName + " "
+ "OR " + searchColumn + " = " + strParamName + ") ";
}
else
{
strWhereClause += "OR (thisyear." + strKB + " = " + strParamName + " "
+ "OR " + searchColumn + " = " + strParamName + ") ";
}
}
}

SQL unable to cast object of type 'system.string' to type 'system.iformatprovider' error in vb.net

I am trying to run this Query in my VB Application but receive an error saying:
unable to cast object of type 'system.string' to type 'system.iformatprovider'
SQL = "insert into billing_pdf_archive (reseller_sequence, invoice_number, pdf, worddoc, csv_cdr_file, csv_services_file, sub_total, vat_amount, grand_total, invoice_type, directdebit) values ('" + reseller.ToString + "','" + invoice_number.ToString + "', '" + Replace(reseller_company_name + "-" + invoice_number + ".pdf", " ", "_") + "', '" + Replace(reseller_company_name + "-" + invoice_number + ".doc", " ", "_") + "', '" + Replace(reseller_company_name + "-" + invoice_number.ToString + "_CDR.xlsx", " ", "_") + "', '" + Replace(reseller_company_name + "-" + invoice_number.ToString + "_Services.xlsx", " ", "_") + "', " + total.ToString("F2") + ", " + vat_amount.ToString("F2") + ", " + grand_total.ToString("F2") + ", 'Month End Reseller', '" + customer_direct_debit + "')"
conn3.ConnectionString = "server=" + global_variables.web_server_ip + "; user id=" + global_variables.web_server_username + "; password=" + global_variables.web_server_password + "; database=" + global_variables.web_server_database + "; "
conn3.Open()
myCommand3.Connection = conn3
myCommand3.CommandText = SQL
myCommand3.ExecuteNonQuery()
conn3.Close()
This is not a complete answer but I'll post it as an answer so that I can post formatted code. If you do as suggested in the comments and write clean, readable code then it will become obvious where the issue is and how to fix it. When you have one line that does lots of different things then working out what on that line is causing an issue is all but impossible. You should use an XML literal for your SQL code, parameters for your values and a connection string builder, e.g.
Dim sql = <sql>
INSERT INTO MyTable
(
Column1,
Column2
)
VALUES
(
#Column1,
#Column2
)
</sql>
command.CommandText = sql.Value
command.Parameters.AddWithValue("#Column1", value1)
command.Parameters.AddWithValue("#Column2", value2)
Dim builder As New SqlConnectionStringBuilder
builder.DataSource = server
builder.InitialCatalog = database
connection.ConnectionString = builder.ConnectionString
Now you'll be able to see exactly what part of your code is causing the issue and, if you still can't solve it yourself, will be able to point out where the issue is to us instead of expecting us to read that dog's breakfast.

Execute all Query or Nothing Should get executed

Well Try to Format Ques.I have set of Queries mentioned below.Now i want to have some functionality which can ensure either all query should execute or not even one(if some kind of error occur) i just want to maintain my database in proper state.
con.setAutoCommit(false);
String qry = "insert into tblAllotment(Employee_ID,Employee_Name,Area,Building_Name,Flat_Type,Flat_No,Date_Application,Date_Allotment,Admin_Code) values(" + id + ",'" + name[1] + "','" + area + "','" + flat[2] + "','" + flat[1] + "','" + flat[0] + "','" + dte + "','" + date + "'," + uid + ")";
String qry1 = "insert into tblFlat_Report(Flat_No,Area_Code,Employee_ID,Date_Allottment,Admin_Code)values('" + flat[0] + "'," + acode + "," + id + ",'" + date + "'," + uid + ")";
//String qry2="UPDATE tblUser_Report t1 JOIN (SELECT MAX(S_Date) s_date FROM tblUser_Report WHERE Employee_ID = "+id+") t2 ON t1.s_date = t2.s_date SET t1.Status = 'A', t1.S_Date ='"+date+"' WHERE t1.Employee_ID ="+id+"";
String qry2 = "insert into tblUser_Report(Employee_ID,Employee_Name,S_Date,Area,Status) values(" + id + ",'" + name[1] + "','" + date + "','" + area + "','A')";
String qry3 = "update tblFlat set Status ='A' where Flat_No='" + flat[0] + "' AND Area_Code=" + acode + " ";
String qry4 = "update tblUser set WL_Flag='N' where Employee_ID=" + id + "";
st = con.createStatement();
int i = st.executeUpdate(qry);
int j = st.executeUpdate(qry1);
int k = st.executeUpdate(qry2);
int l = st.executeUpdate(qry3);
int m = st.executeUpdate(qry4);
con.commit();
if (i != 0 & j != 0 & k != 0 & l != 0 & m != 0) {
Done = "Data Inserted Successfully...!!!";
} else {
System.out.println("Error Occured");
}
} catch (SQLException e) {
con.rollback();
System.out.println(e.getMessage());
}
}
Your database has to provide transactions. If you use MySQL, you cannot use a MyISAM database table, you have to use a InnoDB one (for example).
You begin a transaction at the start of your code, then check each result. If you get an error, you issue a rollback. If everything runs fine, you issue a commit at the end.
Your look should look like:
con.setAutoCommit(false); // at the beginning, to prevent auto committing at each insert/update/delete
// ... your updates, with error checking
con.commit(); // at the end, only if everything went fine.
In case of error, call con.rollback()
Wrap your queries in try catch. Add setAutoCommit(false) at the start of try and commit() at its end, add rollback() in catch block.
try {
conn.setAutoCommit(false);
// Execute queries
conn.commit();
}
catch (SQLException e) {
conn.rollback();
}