How to select by date entered by the user? - mysql

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 ...
}

Related

Query by date with ASP and MySQL

I need to make a query in a MySQL database returning records with the current date.
I found the command below and it works perfectly inside MySQL:
SELECT * FROM TBAvaliacoes WHERE DataHora = (Date_Format(Now(),'%Y-%m-%d'))
But when I do this inside ASP, it returns me the error below:
See how I am doing:
' ## LISTA RAMAIS
Set cmdListaAvaliacoes = Server.CreateObject("ADODB.Command")
cmdListaAvaliacoes.ActiveConnection = conn
cmdListaAvaliacoes.CommandText = "SELECT * FROM TBAvaliacoes WHERE DataHora = (Date_Format("&Now()&",'%Y-%m-%d'))"
response.write cmdListaAvaliacoes.CommandText
cmdListaAvaliacoes.CommandType = 1
Set rsListaAvaliacoes = Server.CreateObject("ADODB.Recordset")
rsListaAvaliacoes.Open cmdListaAvaliacoes, , 3, 3
If I enclose Now () in single quotation marks, it gives no error, but returns nothing.
Does anyone know how to get around this?
Awaiting,
If you want to call the Now() function defined by MySql then you shouldn't use the VB.NET function and concatenate its output to your sql. Just write the code exactly how you write it in the MySql Workbench
cmdListaAvaliacoes.CommandText = "SELECT * FROM TBAvaliacoes
WHERE DataHora = (Date_Format(Now(),'%Y-%m-%d'))"
If you want to pass a particular date then you need to format your date as expected by MySql
Dim myDate As DateTime = new DateTime(2019,8,10)
cmdListaAvaliacoes.CommandText = "SELECT * FROM TBAvaliacoes
WHERE DataHora = '" & myDate.ToString("yyyy-MM-dd") & "'"
But in this case the better approach is to use parameters (even if you have full control of what your date is)
Dim myDate As DateTime = new DateTime(2019,8,10)
cmdListaAvaliacoes.CommandText = "SELECT * FROM TBAvaliacoes
WHERE DataHora = #dat"
Dim prm = cmdListaAvaliacoes.CreateParameter("#dat", adDBDate, adParamInput)
prm.Value = myDate
cmdListaAvaliacoes.parameters.Append prm
Side note
A lot of time has passed from the last time I have used ADODB. So the parameter solution is how I remember it. Search on the net for more complete CreateParameter examples

How to check only month and year in MySQL DateTime column in Vb.net

Im saving some calculated values in to database each month.Before saving, i want to check data is already available for this month and year. IF the same month exists, then user has to select another month or leaving without saving that. In Vb.net, im using DateTimepicker for selecting month and save that in DateTIme format in mysql. In that i want to check only month and year is existing.
Mysql:
1 2019-05-01 14:24:20 ProA 8.34 3.59
2 2019-05-01 14:24:20 ProB 9.21 5.54
Here record available for ProA for May2019 is available. So user cannot save for may 2019 again.
Dim selectedDate = DateTimePicker1.Value
Dim startDate = New Date(selectedDate.Year, selectedDate.Month, 1)
conn.Open()
sQuery = "SELECT * FROM riskanalysis WHERE DATE_FORMAT(reportdate,'%c %Y') >= #StartDate "
cmd_listview = New MySqlCommand(sQuery, conn)
cmd_listview.Parameters.AddWithValue("#StartDate", startDate)
Using reader As MySqlDataReader = cmd_listview.ExecuteReader()
If reader.HasRows Then
' User already exists
MsgBox("Record Already Exist for this Month!", MsgBoxStyle.Exclamation, "Select another month!")
Else
sQuery = "INSERT INTO riskanalysis (reportdate, process, avgrisk, avgriskafterImp) VALUES (#dat, #process, #avgrisk, #riskafterimp);"
For i As Integer = 0 To ProcessRiskGridView.Rows.Count - 1
cmd_listview = New MySqlCommand(sQuery, conn)
cmd_listview.Parameters.AddWithValue("dat", DateTimePicker1.Value)
cmd_listview.Parameters.AddWithValue("process", ProcessRiskGridView.Rows(i).Cells(0).Value)
cmd_listview.Parameters.AddWithValue("avgrisk", ProcessRiskGridView.Rows(i).Cells(1).Value)
cmd_listview.Parameters.AddWithValue("riskafterimp", ProcessRiskGridView.Rows(i).Cells(2).Value)
cmd_listview.ExecuteNonQuery()
Next
End Using
conn.Close()
I tried for some mysql command but it didnt work.
You don't need to Select * to find out if a record exists. Just get the count. Don't retrieve data you don't need. You certainly don't need a reader.
Keep your database objects local so you can be sure they are closed and disposed. `Using...End Using blocks will handle this for you even if there is an error.
Don't use .AddWithValue See http://www.dbdelta.com/addwithvalue-is-evil/
and
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
and another one:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
You keep adding parameters to the collection over and over on each iteration. They only need to be added once. The value of #dat remains the same for all iterations. Only the values of the last 3 parameters change. You seem to be mixing up column names and parameter names. We are dealing with parameter names.
I have guessed at datatypes. Check your database for the actual datatypes and be sure to convert the values from the grid cells to the proper type if necessary. I don't know what kind of grid you are using and if it returns proper datatypes for .Value.
Example:
cmd.Parameters("#avgrisk") = CDbl(ProcessRiskGridView.Rows(i).Cells(1).Value)
Private Sub MySql()
Dim retVal As Integer
Dim selectedDate = DateTimePicker1.Value
Dim startDate = New Date(selectedDate.Year, selectedDate.Month, 1)
Dim sQuery = "SELECT Count(*) FROM riskanalysis WHERE DateTimeColumnName >= #StartDate; "
Using conn As New MySqlConnection("Your connection string")
Using cmd As New MySqlCommand(sQuery, conn)
cmd.Parameters.Add("#StartDate", MySqlDbType.DateTime).Value = startDate
conn.Open()
retVal = CInt(cmd.ExecuteScalar)
End Using
End Using
If retVal <> 0 Then
MessageBox.Show("Record Already Exist for this Month!")
Return
End If
sQuery = "INSERT INTO riskanalysis (reportdate, process, avgrisk, avgriskafterImp) VALUES (#dat, #process, #avgrisk, #riskafterimp);"
Using cn As New MySqlConnection("Your connection string")
Using cmd As New MySqlCommand(sQuery, cn)
With cmd.Parameters
.Add("#dat", MySqlDbType.DateTime).Value = selectedDate
.Add("#process", MySqlDbType.VarChar)
.Add("#avgrisk", MySqlDbType.Double)
.Add("#riskafterimp", MySqlDbType.Double)
End With
cn.Open()
For i As Integer = 0 To ProcessRiskGridView.Rows.Count - 1
cmd.Parameters("#process").Value = ProcessRiskGridView.Rows(i).Cells(0).Value
cmd.Parameters("#avgrisk") = ProcessRiskGridView.Rows(i).Cells(1).Value
cmd.Parameters("#riskafterimp") = ProcessRiskGridView.Rows(i).Cells(2).Value
cmd.ExecuteNonQuery()
Next
End Using
End Using
End Sub

How to find the total rows in a database

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.

How to check more column values at a time in sqlserver 2008?

my table:
id address tag
1 test class1
2 test1 class2
3 test3 class3
In UI i am displaying all tag names as checkboxes.
When user selects one or more tag names then need to get required address values. how to get?
if user selects class1,class2 in UI then need to get test,test1 as result.
Please tell me how to write query in sqlserver 2008 for that.
EDIT CODE :
taglist = "class1,class2";
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
SqlCommand cmd = new SqlCommand("usp_GetTags", con);
cmd.Parameters.Add("#Tags", SqlDbType.VarChar).Value = taglist;
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
while passing the parameters as above not getting any results.if i pass single taglist=class1 getting results.but taglist="class1,class2" not getting any resuls.please tell me how to pass multiple parameters from UI.
You can write the query in sql server by using the IN keyword.
Select address from mytable where tag IN ('class1','class2')
EDIT:
Add the parameters with values to the stored procedure like this. The below code is written in C#.net
comand.Parameters.AddWithValue("#Parameter1", "class1");
comand.Parameters.AddWithValue("#Parameter2", "class2");
EDIT 2:
Its very simple to put in a single string all the values, accordingly your query also suits that. Write the query in your stored procedure like
Select address from mytable where tag IN (#SingleParameter)
and in your coding part write like follow
string SingleParameter = "";
SingleParameter = "class1,class2,class3";
comand.Parameters.AddWithValue("#SingleParameter",SingleParameter);
EDIT 3:
Finally i found the solution for your problem. Write your stored procedure as below
ALTER PROCEDURE dbo.TestSP
/*
(
#parameter1 int = 5,
#parameter2 datatype OUTPUT
)
*/
#SingleParameter varchar(30)
AS
/* SET NOCOUNT ON */
declare #tags varchar(500)
set #tags = #SingleParameter
create table #t (tag varchar(10))
set #tags = 'insert #t select ' + replace(#tags, ',', ' union select ')
exec(#tags)
Select address from sample1 where (tag in (select tag from #t))
drop table #t
RETURN
and also send the parameters SingleParameter as below
string SingleParameter = "";
SingleParameter = "'class1','class2','class3'";
comand.Parameters.AddWithValue("#SingleParameter",SingleParameter);

I need the metadata from a mysql resultset, is this possible?

I'd like to obtain the metadata from the results of a mysql query so I can put it into a datatable in c#. I primarily need the column name and the data type. Here's a simple example.
show columns from (
select sum(subtotal) as subtotal
, sum(tax1+tax2+tax3+tax4) as tax
, sum(subtotal)+sum(tax1+tax2+tax3+tax4) as total
from tbltransmaster
where batchnum in (
SELECT BatchNum
FROM tblshiftmaster
WHERE ClosingTS <> -1
ORDER BY OpeningTS ASC
)
) as x
It generates this error though
Error Code : 1064 You have an error in
your SQL syntax; check the manual that
corresponds to your MySQL server
version for the right syntax to use
near '(
select sum(subtotal) as subtotal
, sum(tax1+tax2+tax3+tax4) as tax
, sum' at line 1
Could someone provide me with some advice, or perhaps a link to assist with this?
show columns only works for actual tables and views, not for queries.
Since you mention C#, you're probably using ADO.NET ? You can directly fill a DataTable which figure out the data types and column names.
DbConnection conn = null;
DbConnection conn = null;
DbCommand cmd = null;
DbDataAdapter da = null;
DataTable tbl = new DataTable();
conn = new MySqlConnection(connectionString);
conn.Open();
cmd = conn.CreateCommand();
cmd.CommandText = query;
da = new MySqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(tbl);
If you want to get the colum names only, you could fetch the result using a DataReader instead:
DbDataReader dbReader = cmd.ExecuteReader();
for (int i = 0; i < dbReader.FieldCount; i++) {
Type colType = dbReader.GetFieldType(i);
String colName = dbReader.GetName(i);
}
DbDataReader also have the .GetSchemaTable() which returns a DataTable describing the metadata of the result.