Windows App c# SQLlite Database Query - c#

Really new to SQL and I have spent days trying to do queries in my windows store app but can not get the where clause to work
I use the following code to query my database
string query = string.Empty;
public async Task<List<CityClass>> GetListCities(int fred)
{
List<CityClass> objLstCoty = new List<CityClass>();
try
{
query = "Select " + DBColumns.Id + "," + DBColumns.WORKNUM + "," + DBColumns.FAULTREF + " from " + DataBaseWrapper.Cities;
objLstCoty = await con.QueryAsync<CityClass>(query);
tb1.Text = "ID: " + objLstCoty[fred].Id;
tb2.Text = "Fault Ref: " + objLstCoty[fred].FAULTREF;
tb3.Text = "Work Number: " + objLstCoty[fred].WORKNUM;
}
catch (Exception ex)
{
//return null;
throw ex;
}
return objLstCoty;
}
This query 3 columns in my database and puts the data into 3 textboxs
How do I add a where statement so that it only returns the data where the WORKNUM equals a certain number eg WORKNUM = "112000"
I Thought adding + " where " + DBColumns.WORKNUM = "112000"; would work but it does not
Any Help is appreciated
Mark

Thanks for all your help guiding me in the right direction I managed to get it to work using
var ITEM = db.Query("Select * From Cities where WORKNUM='" + srcnum + "' ").FirstOrDefault();
where srcnum is the number i wanted to search for in the WORKNUM column
i can then just fill the textblocks using item.[columnname]
Mark

Looking at how you would add that WHERE clause to the end of your query, it wouldn't even compile as the = sign is outside of the string you're building up.
Try doing the following:
query = "Select " + DBColumns.Id + "," + DBColumns.WORKNUM + "," + DBColumns.FAULTREF + " from " + DataBaseWrapper.Cities + " where " + DBColumns.WORKNUM + " = 112000";

Related

How to combine two SQLite statements running in C#?

I have these two statements:
db2.Execute(" UPDATE CLICKHISTORY SET " +
" DAYOFYEAR = " + dayOfYear + " , " +
" YEAR = " + year + " , " +
" MONTH = " + month + " , " +
" DAY = " + day + " , " +
" BTNACOUNT = BTNACOUNT + 1 WHERE YYMMDD = " + yymmdd );
db2.Execute(" INSERT INTO CLICKHISTORY " +
" (YYMMDD,DAYOFYEAR,YEAR,MONTH,DAY,BTNACOUNT) " +
" VALUES ( " +
yymmdd + " , " +
dayOfYear + " , " +
year + " , " +
month + " , " +
day + " , " +
"1) WHERE changes() = 0");
What I would like to do is to check if changes() = 0 in the first statement before running the second statement.
Can anyone tell me how I can group together these two statements in to one so I can check the value of changes()?
Assuming db2 is of type SQLite.SQLiteConnection, you can use the return value of the Execute method to find out the number of affected rows - something like:
int rowsAffected = db2.Execute("UPDATE...");
if (rowsAffected == 0) {
rowsAffected = db2.Execute("INSERT...");
}
In general, you can combine sqlite statements using semicolon ;.
But as I understand, the real question here is: How to conditionally insert values in SQLite?
You cannot use WHERE with INSERT INTO table VALUES(...), but use can use INSERT INTO table SELECT ... syntax instead and add a WHERE clause to select.
Example
Let's say I have a simple table: scores (name varchar(20), score int). I want to update a row or insert a new one if there's nothing to update yet.
var name = "my team";
var sql = $"update scores set score = score+1 where name = '{name}';"
+ $"insert into scores(name, score) select '{name}', 0 where changes() = 0" ;
var cmd = new SQLiteCommand(sql, conn);
cmd.ExecuteNonQuery();
Depending on the driver you use, the C# methods used may differ - I'm using System.Data.Sqlite here.
You may also want to taka look at how to do Upsert in SQLite.

Issues with the update query SQL

am writing a c# code in which am trying to update 4 of the 10 columns of the table. Here is my function type in which am sending arguments for the query:
public int checkout_visitor(int check_inn, int checkout, String time_out, String date_out, String cnic)
Now what happens is that i call this function somewhere in my program providing values in argument:
checkout_visitor(chk_in,chk_out,t_out,dt_out,idcardnum);
The query am using to update my columns is given by:
String query2 = " UPDATE visit_detail SET[check_in] = " + check_inn + "[check_out] = " + checkout + "[time_out] = " + time_out + "[date_out] =" + date_out + "where visit_detail.v_id = "+ v_idd;
Given me exception incorrect syntax near chkout. Where am i wrong?? is the syntax correct? how do i correct it?
code:
public int checkout_visitor(int check_inn, int checkout, String time_out, String date_out, String cnic)
{
try
{
connection.Open();
String query = "select v_id from visitor where visitor.cnic=" + cnic;
command = connection.CreateCommand();
command.CommandText = query;
visitor_id = command.ExecuteScalar().ToString();
int v_idd = Int32.Parse(visitor_id);
String query2 = " UPDATE visit_detail SET[check_in] = " + check_inn + "[check_out] = " + checkout + "[time_out] = " + time_out + "[date_out] =" + date_out + "where visit_detail.v_id = " + v_idd;
//String query2 = "UPDATE visit_detail SET [check_in] = " + check_inn + ",[check_out] = " + checkout + ",[time_out] = " + time_out + ",[date_out] =" + date_out + " where visit_detail.v_id = " + v_idd;
command = connection.CreateCommand();
command.CommandText = query2;
int result = command.ExecuteNonQuery();
connection.Close();
return result;
}
catch (Exception e)
{
return -1;
}
}
Problem :
1.you are not seperating the Parameters properly using comma , .
2.you are not giving the sapace between SET and check_in parameter.
Try This:
String query2 = "UPDATE visit_detail SET [check_in] = " + check_inn + ",[check_out] = " + checkout + ",[time_out] = '" + time_out + "',[date_out] ='" + date_out + "' where visit_detail.v_id = "+ v_idd;
Do you see the resulting query? It seems to me you're missing some comma, but you should print (and post) the resulting query to have a better understanding of the issue.
You are missing ',' between the column names.
Its like Update Table Set col1=3,col2='test'
The problem is that query2 string will be something along the lines:
UPDATE visit_detail SET[check_in] = " 1[check_out] = 2[time_out] = some time[date_out] =some datewhere visit_detail.v_id = 5
So you can already see that there's datewhere that is incorect, there are also no ' characters around string parameters, and no commas between parameters.
Quick fix to that would be:
String query2 = String.Format("UPDATE visit_detail SET [check_in]={0}, [check_out]={1}, [time_out]='{2}', [date_out]='{3}' where visit_detail.v_id={4};", check_inn, checkout, time_out, date_out, v_idd);
But this is still not valid. If time_out contains ' characters, you'll again receive an error.
What you should really use is this:
SqlCommand.Parameters
This is a proper way of passing paramters to your command, all the problems will be taken care of for you.

SQL query for a database with two many-to-many relationships in a 'loop'

Firstly apologies for the woolly subject title, its hard to put this one into words.
So…with that in mind I’ve attached a database relationship diagram (see below) which will hopefully explain it much more concisely.
We have inherited a large database (and therefore have no ability to change/rationalise it, more’s the pity!) which has a troublesome ‘loop’ of 4 tables that have a couple of different many to many relationships within.
I need to be able to get out the Court’s name, full address, and general notes, all of which every court will only have one of, followed by the Contact details which are divided into two groups (general and specific contact points) which could contain one or more listings dependent on the court. I need this to appear in the format below:
Abergavenny Magistrates' Court
Abergavenny
NP7 5DL
This court is open for hearings only. Additional Court Notes….
Contacts
Switchboard: 01633 64xxxx
Fax: 01633 64xxxx
Service 1: 01633 64xxxx
Service 2: 01633 64xxxx
Contact Name 1 - Acting Court Manager: 01633 64xxxx
Contact Name 2 - Acting Office Manager: 01633 64xxxx
Contact Name 3 - Acting List Officer: 01633 64xxxx
Contact Name 4 - Justices' Clerk: 01633 64xxxx
I posted on StackOverflow yesterday to find out how to correctly write the SQL query and ASP.NET C# code for one many-to-many relationship. For simplicity’s sake the info I provided was very much paraphrased and basically contained only half of the loop you see above. However I’ve since failed in my attempt to apply the same principles to the full loop.
The SQL query (which works for the first half of the loop, i.e. to provide the court address details and a list of the specific contact points) looks like this:
string myQuery =
"SELECT C.court_id, court_name, court_addr1, court_town_name, court_county_name, " +
"court_country_name, court_addr_pcode, court_addr_dx, court_code, court_note, " +
"court_contacts_name, court_contacts_no, CCT.court_contact_type_desc " +
"FROM court C " +
"JOIN court_addr CA ON C.court_addr_id = CA.court_addr_id " +
"JOIN court_town CT ON CA.court_town_id = CT.court_town_id " +
"JOIN court_county CC ON CT.court_county_id = CC.court_county_id " +
"JOIN court_country CCO ON CC.court_country_id = CCO.court_country_id " +
"JOIN court_contacts CCON ON C.court_id = CCON.court_id " +
"JOIN court_contact_type CCT ON CCON.court_contact_type_id = CCT.court_contact_type_id " +
"WHERE C.court_id = '25' " +
"ORDER BY C.court_id";
Whilst the C# looks like this:
if (myDataReader.HasRows)
{
string last_id = string.Empty;
while (myDataReader.Read())
{
string court_id = myDataReader["court_id"].ToString();
string court_name = myDataReader["court_name"].ToString();
string court_addr = myDataReader["court_addr1"].ToString();
string court_town = myDataReader["court_town_name"].ToString();
string court_county = myDataReader["court_county_name"].ToString();
string court_country = myDataReader["court_country_name"].ToString();
string court_pcode = myDataReader["court_addr_pcode"].ToString();
string court_dx = myDataReader["court_addr_dx"].ToString();
string court_code = myDataReader["court_code"].ToString();
string court_note = myDataReader["court_note"].ToString();
string court_contact_name = myDataReader["court_contacts_name"].ToString();
string court_contact_desc = myDataReader["court_contact_type_desc"].ToString();
string court_contact_no = myDataReader["court_contacts_no"].ToString();
if (last_id != court_id) {
Response.Write("<strong>" + court_name + "</strong><br>" + court_addr +
"<br>" + court_town + "<br>" + court_county + "<br>" +
court_country + "<br>" + court_pcode + "<br><br>" +
court_dx + "<br><p>Court code " + court_code + "</p><p>" +
court_note + "</p>" + court_contact_name + " - " +
court_contact_desc + ": " + court_contact_no + "<br>");
} else {
Response.Write("<br>" + court_contact_name + " - " + court_contact_desc +
": " + court_contact_no + "<br>");
}
last_id = court_id;
}
}
Following the same logic in the SQL query I’ve tried to add an additional SELECT parameter of court_contacts_general_no and a couple of extra JOIN lines to bring in the court_contacts_general table (see below), however, this produces errors along the lines of ‘The correlation name CCG is specified multiple times in a FROM clause’ or just goes completely blank if the 2nd correlation name is removed.
"JOIN court_contacts_general CCG ON C.court_id = CCG.court_id " +
"JOIN court_contacts_general CCG ON CCT.court_contact_type_id = CCG.court_contact_type_id " +
Whilst in the C# I’ve added a new string for court_contact_general_no and tried creating another if/else loop based on writing the response received from this new variable.
Either way, all I’m getting is a big blank page or the SQL related errors above.
Any ideas?
Thanks in advance for all/any help.
You'll need to use different table name aliases in order to join the same table more than one time in a single query
JOIN court_contacts_general CCG1
JOIN court_contacts_general CCG2.. etc
I'd recommend naming the tables something more relevant to what data is being returned though in that case
It's certainly not elegant (no doubt there's a much better way of writing it!) but I've managed to work out a solution to the problem by writing a second SQL query and opening a second Sqlconnection directly after the first one has closed to tag on the second batch of contacts.
SQL query:
string myQuery2 =
"SELECT C.court_id, court_contacts_name, court_contacts_no, court_contact_type_desc " +
"FROM court C " +
"JOIN court_contacts CCON ON C.court_id = CCON.court_id " +
"JOIN court_contact_type CCT ON CCON.court_contact_type_id = CCT.court_contact_type_id " +
"WHERE C.court_id = '" + court_id_no + "' " +
"ORDER BY C.court_id";
C# code:
myDataReader.Close();
connection.Close();
SqlConnection connection2 = new SqlConnection(connStr);
SqlCommand myCommand2 = new SqlCommand(myQuery2, connection2);
SqlDataReader myDataReader2;
connection2.Open();
myDataReader2 = myCommand2.ExecuteReader();
if (myDataReader2.HasRows) {
string last_id = string.Empty;
while (myDataReader2.Read()) {
string court_id = myDataReader2["court_id"].ToString();
string court_contact_desc = myDataReader2["court_contact_type_desc"].ToString();
string court_contact_name = myDataReader2["court_contacts_name"].ToString();
string court_contact_no = myDataReader2["court_contacts_no"].ToString();
if (string.IsNullOrWhiteSpace(court_contact_no)) {
court_contact_no = generic_contact_no;
}
if (last_id != court_id) {
Response.Write(court_contact_name + " - " + court_contact_desc + ": " + court_contact_no + "<br>");
} else {
Response.Write(court_contact_name + " - " + court_contact_desc + ": " + court_contact_no + "<br>");
}
last_id = court_id;
}
}
As I say, not pretty but the important thing is it works.

Update/Insert into table

I have to update table on SQL Server but first i have to check for existing data in table so if data is there update it, if not make a new insert:
cmd_sql.CommandText = " SELECT BrDok as id_dok " +
" FROM ordersstavke " +
" WHERE SifParFil = '" + rw_mat["sifskl_kor"] + "'" +
" AND DokumentTip = '" + rw_mat["vrst_dok"] + "'";
MySqlDataAdapter sql_adapter = new MySqlDataAdapter(cmd_sql);
DataSet dt_dok = new DataSet("DOK_MAT_EXCHANGE");
sql_adapter.Fill(dt_dok);
if (dt_dok.Tables["DOK_MAT_EXCHANGE"].Rows.Count == 0)
{
myQuery = " INSERT INTO ordersstavke (BrDok, DocumentTip, SifParFil) " +
" VALUES ('" + rw_mat["brdok"] + "', '" +
rw_mat["vrst_dok"] + "', '" +
rw_mat["sifskl_kor"] + "')";
}
else
{
UPDATE DATA
}
But I have an error in the code, the error is here if (dt_dok.Tables["DOK_MAT_EXCHANGE"].Rows.Count == 0)
Object reference not set to an instance of an object.
The problem is in this if statement...
DOK_MAT_EXCHANGE is the name of the DataSet, not of the first table.
You should test with
if (dt_dok.Tables[0].Rows.Count == 0)
Also, I think is better to use a syntax like this to discover how many records are presents
cmd_sql.CommandText = "SELECT COUNT(BrDok) as id_dok " +
" FROM ordersstavke " +
" WHERE SifParFil = ?p1 " +
" AND DokumentTip = ?p2";
cmd_sql.Parameters.AddWithValue("?p1", rw_mat["sifskl_kor"] );
cmd_sql.Parameters.AddWithValue("?p2", rw_mat["vrst_dok"] );
int rowCount = (Int32)cmd_sql.ExecuteScalar();
change
DataSet dt_dok = new DataSet("DOK_MAT_EXCHANGE");
to
DataSet dt_dok = new DataSet("ordersstavke ");
and
if (dt_dok.Tables["DOK_MAT_EXCHANGE"].Rows.Count == 0)
to
if (dt_dok.Tables["ordersstavke "].Rows.Count == 0)
Accessing the first table via the dataset name is incorrect, that's for setting the XML.
Instead use
dt_dok.Tables[0].Rows.Count;
That being said, you're better off writing this as a single SQL statement instead of a separate select && insert. This way you're not going to the DB multiple times.
var sql = #"if exists(select * from ordersstavke where SifParFil = ? and DokumentTip = ?)
then
-- do insert statement
else
-- do update
end if";
This might also be better done with a stored proc, so you don't have as much SQL code in C#. It's easier to manage multiple operations that way.
And for crying out loud, use SqlParameters, not string concatenation! That's just asking for trouble!
Ok, thanks guys, I wrote it like this
if (ds_dok.Tables[0].Rows.Count <= 0)
{
myQuery = " INSERT INTO ordersstavke (BrDok, " +
" SifParFil) " +
" VALUES ('" + rw_mat["brdok"] + "', '" +
rw_mat["sifskl_kor"] + "')";
}
else if (ds_dok.Tables[0].Rows.Count >= 1)
{
myQuery = "UPDATE ordersstavke " +
"SET BrDok = '" + rw_mat["brdok"] + "', " +
"SifParFil = '" + rw_mat["sifskl_kor"] + "', " +
"WHERE BrDok = " + ds_dok.Tables["ordersstavke"].Rows[0]["BrDok"].ToString() + "'";
}
But there is a small problem in the section update: s_dok.Tables["ordersstavke"].Rows[0]["BrDok"].ToString(), here it give me that loving error : Object reference not set to an instance of an object.
Maybe the update on MySQL goes on different way, I'm referencing on example on sql server and there update goes differently

How can you use parameterized statements with DB2 Text Search?

I've tried this:
select * from ourschema.mytable
where contains(mysearchablefield, #searchTerms) = 1;
Where #searchTerms was set to "search terms"
Unfortunately, it only produced an error:
ERROR [42610] [IBM][DB2/NT] SQL0418N A statement contains a use of a parameter marker that is not valid. SQLSTATE=42610
Is there a way to use parameterized queries for text search with DB2? If not, is there a document which describes the syntax in detail for manual (ugh) escaping of the search terms (quotes, etc)?
Instead of #field you need to use "?". Everything is basically the same.
Okay, here is a live code sample.
sqlStmt = "SELECT COMPLAINT_NUMBER, VIOLATION_NUMBER, COMMON_ADDRESS_KEY, " +
"DEPT_CODE, DEPT_CODE_DESC, DIVISION_CODE, DIVISION_CODE_DESC, " +
"EMPLOYEE_NAME, COMPLAINT_CODE, COMPLAINT_CODE_DESC, COMPLAINT_DATE, " +
"COMMON_ADDRESS_OWNER, RESOLUTION_CODE, 1 AS SORTORDER " +
"FROM QMFILES/NVMASTP " +
"WHERE VCLOSEDATE = 0 AND " +
"DEPT_CODE LIKE #DEPT_CODE1 AND " +
"DIVISION_CODE LIKE #DIVISION_CODE1 AND " +
"COMPLAINT_DATE BETWEEN #FROM_COMPLAINT_DATE1 AND #TO_COMPLAINT_DATE1 " +
statusQry +
"UNION " +
"SELECT COMPLAINT_NUMBER, VIOLATION_NUMBER, COMMON_ADDRESS_KEY, " +
"DEPT_CODE, DEPT_CODE_DESC, DIVISION_CODE, DIVISION_CODE_DESC, " +
"EMPLOYEE_NAME, COMPLAINT_CODE, COMPLAINT_CODE_DESC, COMPLAINT_DATE, " +
"COMMON_ADDRESS_OWNER, RESOLUTION_CODE, 2 AS SORTORDER " +
"FROM QMFILES/NVMASTP " +
"WHERE VCLOSEDATE <> 0 AND " +
"DEPT_CODE LIKE #DEPT_CODE2 AND " +
"DIVISION_CODE LIKE #DIVISION_CODE2 AND " +
"COMPLAINT_DATE BETWEEN #FROM_COMPLAINT_DATE2 AND #TO_COMPLAINT_DATE2 " +
statusQry +
"ORDER BY DEPT_CODE, DIVISION_CODE, COMPLAINT_CODE, SORTORDER";
iDB2Command cmd = new iDB2Command(sqlStmt, conn);
conn.Open();
cmd.DeriveParameters();
conn.Close();
cmd.Parameters["#DEPT_CODE1"].Value = dept;
cmd.Parameters["#DIVISION_CODE1"].Value = serviceArea;
cmd.Parameters["#DEPT_CODE2"].Value = dept;
cmd.Parameters["#DIVISION_CODE2"].Value = serviceArea;
cmd.Parameters["#FROM_COMPLAINT_DATE1"].Value = Convert.ToDecimal(fromDateString);
cmd.Parameters["#TO_COMPLAINT_DATE1"].Value = Convert.ToDecimal(toDateString);
cmd.Parameters["#FROM_COMPLAINT_DATE2"].Value = Convert.ToDecimal(fromDateString);
cmd.Parameters["#TO_COMPLAINT_DATE2"].Value = Convert.ToDecimal(toDateString);
I hope this helps you out more.

Categories

Resources