How to find the total rows in a database - mysql

I had a look at the other topics here on getting row numbers but couldn't fully understand them. All I need is a way of getting the total number of rows.
I have the following code that reads each row and populates a listbox, however as I want to assign that rows value to an array. I need to know the row number so I can use a 2-dimentional array, where each row data is stored separately in the array.
query = "SELECT * FROM bbs_test.test"
command = New MySqlCommand(query, Sqlconn)
reader = command.ExecuteReader
While reader.Read
arraynames = reader.GetString("data_array")
ListBox_displayarray.Items.Add(arraynames)
End While
Is there a way to get the total row number.
Please could any help
Thank you
After looking at the suggestions I have tried it out and this is how my code looks like
Sqlconn.Open()
Dim querycount As String
querycount = "SELECT count(*) FROM bbs_test.test"
command = New MySqlCommand(querycount, Sqlconn)
reader = command.ExecuteReader
While reader.Read
MessageBox.Show(reader.GetString("data_array"))
End While
The following error occurs
"An unhandled exception of type 'System.IndexOutOfRangeException' occurred in MySql.Data.dll
Additional information: Could not find specified column in results"
I checked and made sure the name of the column is data_array.
Could anyone help me please.

Use
query = "SELECT COUNT(*) FROM bbs_test.test"
This will fetch the count of total number of rows in your table

you need to run the query,
queryCount = "SELECT count(*) FROM bbs_test.test"
command = New MySqlCommand(queryCount, Sqlconn)
var totalRow = command.ExecuteScalar()
In variable totalRow , you have your no. of rows.

Related

passing an Array as a Parameter to be used in a SQL Query using the "IN" Command

Good Afternoon to All,
I have a question concerning on SQL Queries. is it possible to use an array as a parameter to a query using the "IN" command?
for example,
int x = {2,3,4,5}
UPDATE 'table_name' set 'field' = data WHERE field_ID IN (x)
the reason I am asking this is to avoid an iterative SQL Statement when I have to update data in a database.
I also thought of using a for each statement in for the UPDATE Query but I don't know if it will affect the performance of the query if it will slow down the system if ever 100+ records are updated.
I am using VB.Net btw.
My Database is MySQL Workbench.
I have gotten the answer. I just simply need to convert each elements to a String then concatenate it with a "," for each element. so the parameter that i will pass will be a string.
ANSWER:
int x = {2,3,4,5}
will become
string x = "2,3,4,5"
My Query string will become "UPDATE tablename SET field=value WHERE ID IN("&x&")"
Thank you to all who helped.
If you have the query in a variable (not a stored procedure) and you don't have a huge amount of ids, you could built your own IN. I haven't tested the speed of this approach.
This code won't compile, it's just to give you an idea.
query = "SELECT * FROM table WHERE col IN ("
For t = 0 TO x.Length-1
If t > 0 Then query &= ","
query &= "#var" & t
Next
query &= ")"
...
For t = 0 TO x.Length-1
cmd.Parameters.Add("#var" & t, SqlDbType.Int).Value = x(t)
Next
i am not familiar with mySQL, but when dealing with MSSQL, I normally have a split function in DB so that I can use it to split concatenated integer values as a table, at VB side, something like:
Dim myIds = {1, 2, 3, 4}
Dim sql = <sql>
SELECT m.* FROM dbo.tblMyData m
INNER JOIN dbo.fncSplitIntegerValues(#Ids, ',') t ON t.id = m.Id
</sql>.Value
Using con As New SqlConnection("My connection string..."),
cmd As New SqlCommand(sql, con)
cmd.Parameters.Add("#Ids", SqlDbType.VarChar).Value =
myIds.Select(Function(m) m.ToString).Aggregate(Function(m, n) m & "," & n)
con.Open()
Dim rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
While rdr.Read()
Console.WriteLine(rdr.GetValue(0))
' do something else...
End While
End Using
dbo.fncSplitIntegerValues is a db function to split concatenated integer varchar into integer Id with given separator.
it's important not to use plain sql, instead, use sql parameters.
Note: above sample is not tested...

How to use last_insert_id() with "ADODB.Connection" object correctly?

I'm having a problem in retrieving last record id from database. This code below, is the closer I can get. But still, it return record id, as 0; ,then when I execute again, it will return, record of previous execute, not the current one.
sql = "insert into program (prog_det,budget,prog_obj,outcome,target_group,awareness,engagement,issue,seq_no) value ('"&prog_title&"','"&prog_budget&"','"&prog_obj&"','"&prog_result&"','"&prog_target&"','"&prog_aware&"','"&prog_involment&"','"&prog_issues&"','99');"
sql2 = "select last_insert_id() as last_id"
set kpi_prog_conn=Server.CreateObject("ADODB.Connection")
set kpi_prog_rs=Server.CreateObject("ADODB.Recordset")
kpi_prog_conn.Open ObjConn
kpi_prog_conn.Execute(sql)
kpi_prog_conn.Open sql2,objConn,adLockPessimistic
response.write kpi_prog_rs("last_id")
Your penultimate line looks wrong
Try
kpi_prog_rs.Open sql2,kpi_prog_conn,adLockPessimistic
IS the ID you are trying to retrieve is the Primary key of the corresponding table? Try using Scope_Identity() instead of last_insert_id()
Query - SELECT SCOPE_IDENTITY() AS [LAST_IDENTITY]
It returns you the last inserted id into the table
I don't have mysql but try:
sql2 = "select last_insert_id() as last_id;"
sql = "insert into program (prog_det,budget,prog_obj,outcome,target_group,awareness,engagement,issue,seq_no) value ('"&prog_title&"','"&prog_budget&"','"&prog_obj&"','"&prog_result&"','"&prog_target&"','"&prog_aware&"','"&prog_involment&"','"&prog_issues&"','99');" & sql2
set kpi_prog_conn=Server.CreateObject("ADODB.Connection")
kpi_prog_conn.Open ObjConn
set kpi_prog_rs = kpi_prog_conn.Execute(sql)
anotherRecordset = kpi_prog_rs.NextRecordset
response.write anotherRecordset("last_id")

vb.net how to create a variable to count entries going in as inserts and updates

I have a mysql database and a gridview. Now I want to count my inserts and updates. It has been suggested to set up a variables to represent each element e.g. nUpdates and nInserts, but I am unsure on how to do this? Here is the code I am using
For i = 0 To DataGridView1.RowCount - 1
Using dbSQL_cmd As New MySqlCommand()
student_id = DataGridView1.Item(i, 0).Value.ToString
name = DataGridView1.Item(i, 1).Value.ToString
age = DataGridView1.Item(i, 2).Value.ToString
adress = DataGridView1.Item(i, 3).Value.ToString.ToLower
dbSQL_query = "INSERT INTO student VALUES (?id, ?name, ?age, ?adress) " +
" on duplicate key update name=(name=?name, age=?age, adress=?adress)"
With dbSQL_cmd
.Parameters.AddWithValue("?id", student_id)
.Parameters.AddWithValue("?name", name)
.Parameters.AddWithValue("?age", age)
.Parameters.AddWithValue("?adress", adress)
' .Parameters.AddWithValue("?status", ?????)
.CommandText = dbSQL_query
.Connection = SQLConnection
.CommandType = CommandType.Text
End With
dbSQL_cmd.ExecuteNonQuery()
End Using
Next
First, check the number of rows in the table before and after your insert/update loop. The difference between them is the number of rows you inserted.
You know how many items there are in your gridview. From your code, each one is either an insert or an update, so subtract the number of inserts you did (from that first step) from the number of items, and that is the number of rows you updated.

Convert a databound combobox's data to ProperCase in VB 2010

In VB 2010 I'm trying to show the DisplayMember in ProperCase without modifying my existing MySQL tables.
A snippet of my code looks like this:
Dim sql0 As String = "SELECT business, customer_id FROM customers WHERE cab = '1'"
Dim data0 As New MySqlDataAdapter(sql0, main.conn)
Dim ds0 As New DataSet
ds0.Clear()
data0.Fill(ds0, "customers")
cmb_company.DataSource = ds0
cmb_company.DisplayMember = "customers.business"
cmb_company.ValueMember = "customers.customer_id"
Ive tried something like this:
cmb_company.DisplayMember = StrConv("customers.business_name", VbStrConv.ProperCase)
but this only changes the case of the part in quotes, and not the actual returned values. I also tried querying from MySQL like this:
"SELECT UPPER(business), customer_id FROM customers WHERE cab = '1'"
but this fails to return the "business" field..
I'd love it if my combobox had proper case without changing everything.
I appreciate any suggestions!
Use the second one, but use an alias like this:
"SELECT UPPER(business) AS Business, customer_id FROM customers WHERE cab = '1'"
MySQL documentation:
A select_expr can be given an alias using AS alias_name. The alias is
used as the expression's column name and can be used in GROUP BY,
ORDER BY, or HAVING clauses. For example:
SELECT CONCAT(last_name,', ',first_name) AS full_name FROM mytable
ORDER BY full_name;
It seems a bit silly to use a while loop to achieve this especially after filling the table with an adapter. I suppose I could have just skipped the .fill and added the items manually through the loop, all while ProperCasing them. Anyway, here is my code:
Dim sql1 As String = "SELECT * FROM table"
Dim data1 As New MySqlDataAdapter(sql1, main.conn)
Dim ds1 As New DataSet
ds1.Clear()
data1.Fill(ds1, "table")
cmb_buyout.DataSource = ds1
Dim i As Integer = 0
While i < ds1.Tables(0).Rows.Count
Dim name As String = StrConv(ds1.Tables(0).Rows(i).Item(1).ToString, VbStrConv.ProperCase)
ds1.Tables(0).Rows(i).Item(1) = name
i += 1
End While
cmb_buyout.DisplayMember = "table.buyoutType"
cmb_buyout.ValueMember = "table.id"
To anyone trying to accomplish this, it is probably simpler to just change the case on the entries in the DB. I might just end up doing this!

How to select by date entered by the user?

I am using the below query to run an sql statement. It works fine. I wish to know how I can modify the query to select by a date which the user enters in ASP.NET. This means that I need to modify the part:
WHERE TRANSACTION_DATE = '02-AUG-2006'
Any ideas please?
The query I am using is this:
INSERT INTO TRANSACTION (TRX_UNIT, TRX_DATE, TRX_USR)
SELECT SOURCE_SYSTEM_CHANNEL_CODE, TRANSACTION_DATE, USER_CODE
FROM FCR_TRANSACTION
WHERE TRANSACTION_DATE = '02-AUG-2006'
What about:
// Create a connection object and data adapter
MySqlConnection cnx = new MySqlConnection(connectionString);
// Create a SQL command object
string cmdText = "INSERT INTO TRANSACTION (TRX_UNIT, TRX, TRX_USR) ";
cmdText += "SELECT SOURCE_SYSTEM_CHANNEL_CODE, TRANSACTION_DATE, USER_CODE ";
cmdText += "FROM FCR_TRANSACTION ";
cmdText += "WHERE TRANSACTION_DATE = #TransactionDate";
MySqlCommand cmd = new MySqlCommand(cmdText, cnx);
cmd .Parameters.Add("#TransactionDate", YourDate); // <-- Insert date here
// Set the command type to text
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
you must have a name for the date field where the user enters a date. let us say you decide to name it 'datename'
after that the $_POST("datename") returns the text entered in the field.
so now the WHERE statement becomes
WHERE TRANSACTION_DATE = '$_POST("datename")'
if that doesnt work, try
WHERE TRANSACTION_DATE = $_POST("datename")
all this is assuming you kept method of form transfer as POST....if you have it as GET, simply replace $_POST with $_GET here..
This should work. If it doesnt, my apologies.
If you really want to query by the exact Date, you have to validate the Userinput, and add a parameter
to the query (this is only pseudocode) :
string userInput = txtDate.Text;
DateTime parsedDate;
if (DateTime.TryParse(userInput, out parsedDate)) {
// valid date, add a Parameter to your command
var cmd = ... // create your DB Command here
cmd.CommandText = "SELECT .... WHERE Transaction_Date = #txDate";
cmd .Parameters.Add("#txDate", parsedDate);
// execute your command ...
}