SQL query in Excel table - sql

I am running a query using OleDbCommand in a database in Excel, containing the following columns:
name, city, inhabitants
My code:
Cmd = new OleDbCommand();
Cmd.Connection = Conn;
Cmd.Parameters.AddWithValue("#city", city);
Cmd.CommandText = "Select City, count(habitants) as h from [Sheet1$] where city = #city group by city";
var Reader = await Cmd.ExecuteReaderAsync();
I get this error:
OleDbException: You tried to execute a query that does not include the specified expression 'city' as part of an aggregate function.
Why does this error appear if it contains the city column?

You can probably work around this error by adding GROUP BY to your query:
Cmd.CommandText = "Select City, count(habitants) as h from [Sheet1$] where city=#city group by City";

Use the FIRST() function for the city:
Cmd.CommandText = "SELECT FIRST(city) AS city, COUNT(habitants) AS h FROM [Sheet1$] WHERE city=#city GROUP BY city";

Related

How to pass a date variable to an SQL query in Python

Python3.5
Sql Server 2012 Standard
package is pypyodbc
This Code Works
myConnection = pypyodbc.connect('Driver={SQL Server};'
'Server=myserver;'
'Database=mydatabase;'
'TrustedConnection=yes')
myCursor = myConnection.cursor()
sqlstr = ("Select * From DB.Table1 Where DB.Table1.Date <= '7/21/2016'")
myCursor.execute(sqlstr)
results = myCursor.fetchall()
However, Date must be a variable passed in by users. I made several mods to sqlstr but continue to error on myCursor.execute: "TypeError: bytes or integer address expected instead of tuple instance"
sqlstr = ("Select * From DB.Table1 Where DB.Table1.Date <= %s", '7/21/2016')
Error
sqlstr = ("Select * From DB.Table1 Where DB.Table1.Date <= '%s'", '7/21/2016')
Error
sqlstr = ("Select * From DB.Table1 Where DB.Table1.Date <= ?", "'7/21/2016'")
Error
var1 = "'7/21/2016'"
sqlstr = ("Select * From DB.Table1 Where DB.Table1.Date <= %s", var1)
and several more. However, I am sure there is one correct way...
Thanks for any help!
I am sure there is one correct way
Yes, it's a parameterized query:
date_var = datetime(2016, 7, 21)
sql = """\
SELECT [ID], [LastName], [DOB] FROM [Clients] WHERE [DOB]<?
"""
params = [date_var] # list of parameter values
crsr.execute(sql, params)
for row in crsr.fetchall():
print(row)

Writing SQL statement to select from multiple rows

This might be a silly question to ask. I will appreciate any kind of help.
I'm trying to write a query that count the number of rows based on the logic as below:
count no rows where username = #username and friendsname = #friendsname and username = #friendsname and #friendsname = #username where status = 0
consider the table in the diagram below:
The query should return 1 since id '18' and id '20' have reciprocal values. How will this query be written?
I have written the query as follows which doesn't work:
bool flag = false;
StringBuilder query = new StringBuilder();
query.Append("SELECT Count(id) from friends where username=#username AND friend_username=#friend_username AND username = #friend_username AND friend_username = #username");
query.Append(" AND status=0");
using (SqlConnection con = new SqlConnection(Config.ConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(query.ToString(), con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter("#username", username));
cmd.Parameters.Add(new SqlParameter("#friend_username", friendusername));
if (Convert.ToInt32(cmd.ExecuteScalar()) > 0)
flag = true;
}
}
return flag;
If I'm not mistaken you're trying to count rows given a specific #username and #friendusername that have reciprocal values based on your conditions.
Below query should help, though - I have not tested it in action!
SELECT COUNT(*) as reciprocal_values_no
FROM table_name tbl1
WHERE
username = #username
AND friend_username = #friendusername
AND status = 0
AND EXISTS (
SELECT 1 FROM table_name tbl2 WHERE tbl1.username = tbl2.friend_username AND tbl1.friend_username = tbl2.username )
try this
select username,friend_username,status, count(*)
from table_name
group by username,friend_username,status
having count(*) > 1

Why is there a syntax error in my update statement in vb.net?

I have been working on my Update Sql statement, but cannot find the syntax error in my code. My insert statement is working, and I am selecting their login Id from another form to compare against.
conn.Open()
Dim SqlUpdate As String = "UPDATE tblLogin SET UserPassword =#UserPassword , FirstName =#FirstName , Surname =#Surname , DateofBirth =#DateofBirth , Phonenumber =#Phonenumber , Emailaddress = #Emailaddress , Administrator = #Administrator , Height = #Height , Weight = #Weight , WHERE UserID = #UserID "
Dim SqlCommand As New OleDbCommand
With SqlCommand
.CommandText = SqlUpdate
.Parameters.AddWithValue("#UserPassword", passwordsubmitbox.Text)
.Parameters.AddWithValue("#FirstName", forenamebox.Text)
.Parameters.AddWithValue("#Surname", surnamebox.Text)
.Parameters.AddWithValue("#DateofBirth", DOBselection.Value)
.Parameters.AddWithValue("#Phonenumber", phonenumberbox.Text)
.Parameters.AddWithValue("#Emailaddress", emailadressbox.Text)
.Parameters.AddWithValue("#Administrator", "N")
.Parameters.AddWithValue("#Height", CInt(heightbox.Text))
.Parameters.AddWithValue("#Weight", CInt(weightbox.Text))
.Parameters.AddWithValue("#UserID", Formlogin.UsernameBox1.Text)
.Connection = conn
.ExecuteNonQuery()
End With
conn.Close()
Your query has syntax error remove , after #Weight
Weight = #Weight WHERE UserI ...

existence of particular row in datatable in vb.net windows form

Is it possible to check for existence of a particular row in a datatable?
suppose if there are two rows in datatable, is it possible to check whether the third row exists or not?
For j As Integer = 0 To dtemp.Rows.Count - 1
If dtemp.Rows(j)("empcode").ToString.Trim <> dt.Rows(j)("empcode").ToString.Trim Then
'Insert code
End If
Next
Are you trying to see if your data is existing or not?
Let's say: If you are inserting data in your database, then you can use the textbox property tag to see whether the data is existing or not.
If Me.txtFirstName.Tag = 0 Then
sSQL = "INSERT INTO tblAddressBook ( last_name, first_name, mid_name, birth_date, gender, home_adr, bus_adr, tel_no, mobile_no, email)"
sSQL = sSQL & " VALUES(#last_name, #first_name, #mid_name, #birth_date, #gender, #home_adr, #bus_adr, #tel_no, #mobile_no, #email)"
cmd.CommandText = sSQL
Else
sSQL = "UPDATE tblAddressBook set last_name = #last_name, first_name = #first_name, mid_name = #mid_name, birth_date = #birth_date, gender = #gender"
sSQL = sSQL & " ,home_adr = #home_adr, bus_adr = #bus_adr, tel_no = #tel_no, mobile_no = #mobile_no, email = #email where contact_id = #id"
cmd.CommandText = sSQL
End If
...or else it will update that data in your database. The code above should give you an idea. SINCE you didn't show your code let's talk on this one.
If DataRow.Table.Columns.Contains("column") Then
MsgBox("YAY")
End If

How to pass multiple command in one query?

Hi all how can I write code below more simply? ... so two sql(OleDb) command in one query.
con.open();
cmd.CommandText = "DELETE * FROM Customers WHERE ID_C = 1";
cmd.ExecuteNonQuery();
cmd.Clone();
cmd.CommandText = "DELETE * FROM Books WHERE ID_B = 1";
cmd.ExecuteNonQuery();
cmd.Clone();
con.close();
Provided that you don't need the number of rows affected (returned by ExecuteNonQuery) you can simply put both commands in the same SQL separated by ";"
con.open();
cmd.CommandText = "DELETE * FROM Customers WHERE ID_C = 1; DELETE * FROM Books WHERE ID_B = 1";
cmd.ExecuteNonQuery();
con.close();