Displaying records of a particular month in mysql - mysql

I am trying to fetch records of a particular month from the database and the pattern of the data that column is ""
Query I am using is
select * from table_name WHERE column_name LIKE ''
for the month of September. But this is printing no results.
Please suggest.

Use direct date comparisons! Don't treat dates as strings. So something like:
where column_name >= '2000-09-01' and column_name < '2000-10-01'
Or, if you want all months, then extract the month. The standard function is extract():
where extract(month from column_name) = 9
or:
where month(column_name) = 9
However, the particular function depends on the database (not all databases support all the standard functions).

Building up on the answers and comments above. It seems like you want to use this in your C# code with the user selecting a value from a dropdown. One option would would be something like this:
string monthNumber = valueFromDropdown;
string connectionString = "put you connection string here";
string commandText = "select * from table_name "
+ "where month(column_name) = #MonthNumber";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("#MonthNumber", SqlDbType.Int);
command.Parameters["#MonthNumber"].Value = monthNumber;
try
{
connection.Open();
using(SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

Related

How I can get the correct date of my Mysql query without the query itself subtracting one day to date

My problem is that in a table of my database with 7 columns, I have a column of date type, called "Fecnac". Through MYSQLworkbrench, I execute a simple query:
"SELECT * FROM tblAsegurados ORDER BY Name,Nss"
As a result of this query, the information of my columns or fields of the table is displayed, the table contains a column named "Fecnac" that shows the correct date, for example "2018-12-31".
MYSQLworkbrench Result image
However, I developed an application in intelliJ IDEA to execute the same query, and the query "by itself" returns the date with one day less, that is, it shows "2018-12-30". And so it does with all the dates found in the "Fecnac" column of the "tblAsegurados" table in my database.
public ArrayList<Asegurados> getAseguradosList(){
ArrayList<Asegurados> aseguradosList = new ArrayList<Asegurados>();
Connection connection = getConnection();
var query = "select * from tblAsegurados order by Nombre,Nss";
Statement st;
ResultSet rs;
try{
st = connection.createStatement();
rs = st.executeQuery(query);
Asegurados asegurado;
while(rs.next()){
asegurado = new Asegurados(
rs.getString("Nss"),
rs.getString("Nombre"),
rs.getString("Curp"),
rs.getBoolean("Esposa"),
rs.getInt("Semcot"),
rs.getInt("Hijos"),
rs.getDate("Fecnac"));
aseguradosList.add(asegurado);
System.out.println(asegurado.getFecnac());
System.out.println(rs.getDate("Fecnac"));
System.out.println(rs.getDate(7));
}
} catch (Exception e){
e.printStackTrace();
}
return aseguradosList;
}
The class "Asegurados" has an attribute of type "java.sql.date" defined, to receive "rs.getdate (Fecnac).
For i be sure of the values ​​returned by the query, in my code you can see that I made a "System.out.println" for each field date, and in all three I get the same value from the date with one day less.
Could someone help me know what happens?
Console debug IntelliJ Idea image
I already found the solution. In a part of my code, the parameter of the time zone had it defined as: serverTimezone = UTC
public static Connection getMySQLConnection() throws Exception {
String driver = "com.mysql.cj.jdbc.Driver";
String url = "jdbc:mysql://localhost/imss"+
"?useUnicode=true&useJDBCCompliantTimezoneShift=true"+
"&useLegacyDatetimeCode=false&serverTimezone=America/Mexico_City"+
"&verifyServerCertificate=false"+
"&useSSL=true"+
"&requireSSL=true";
String username = "root";
String password = "juan1980";
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}
I set it to: serverTimezone = america / Mexico_City, which is the zone that corresponds to me, and ready! the date is displayed correctly.

How to execute multiple statement with variables in C# OdbcCommand object

I want to execute below MySql queries at a time through OdbcCommand object within C# as dynamic query, it always fails:
SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
set #row=0;
select * from
(
select #row:=#row+1 as my____row_num,
cities.`cityid`,
cities.`cityname`,
cities.`countryid`,
cities.`countryname` , '1' as my____data_row_created , '1' as
my____data_row_updated from `cities` ) p
where my____row_num>=101 and my____row_num<=200;
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ ;
I'm using below method to execute above MySql queries:
ExcuteCommand(Sql)
{
DataTable dt = new DataTable();
OdbcCommand SQLCommand = new OdbcCommand(Sql);
OdbcConnection Con = new OdbcConnection(ConnectionString);
try
{
Con.Open();
SQLCommand.Connection = Con;
OdbcDataAdapter da = new OdbcDataAdapter(SQLCommand);
da.Fill(dt);
Con.Close();
Con.Dispose();
}
catch
{
try
{
Con.Close();
}
catch { }
throw;
}
return dt;
}
I found solution from here. While executing multiple dynamic MySql statements through ODBC in C# we have two options:
Execute separately every command
Use stored procedures
In my case I'm bound to use dynamic-quires because I'm having only read-access on database.
Solution:
Rather than Declaring variable and set it, I used another technique to use a session variable as a derived table and crossed join it with the main table. See the following query, in my scenario I changes to below MySql query code and removed both SET SESSION related code from the query, and it worked properly:
select * from
(
select #row:=#row+1 as my____row_num,
cities.`cityid`,
cities.`cityname`,
cities.`countryid`,
cities.`countryname` , '1' as my____data_row_created , '1' as
my____data_row_updated from `cities` ,(select #row:=0) as t ) p
where my____row_num>=101 and my____row_num<=200;
I'm not going to attempt to solve your MySQL problem, but your C# code can and should be written better, and since comments are not suited for codes, I thought I'd better write this as an answer.
So here is an improvement to your C# part:
DataTable FillDataTable(string sql)
{
var dataTable = new DataTable();
using(var con = new OdbcConnection(ConnectionString))
{
using(var command = new OdbcCommand(sql, con))
{
using(var dataAdapter = new OdbcDataAdapter(SQLCommand))
{
dataAdapter.Fill(dataTable);
}
}
}
return dataTable;
}
Points of interests:
I've renamed your method to a more descriptive name. ExecuteCommand doesn't say anything about what this method does. FillDataTable is self explanatory.
The using statement ensures the disposing of instances implementing the IDisposable interface - And almost all ADO.Net classes are implementing it.
The disposing of an OdbcConnection also close it, so you don't need to explicitly close it yourself.
There is no point of catching exceptions if you are not doing anything with them. The thumb rule is to throw early, catch late. (actually catch as soon as you can do something about it like write to log, show a message to the user, retry etc').
DataAdapters implicitly opens the Connection object, no need to explicitly open it.
Other two improvements you can do are:
Have this method also accepts parameters.
Have this method also accept the CommandType as a parameter (currently, using a stored procedure with this will not work since the default value of CommandType is Text
So, an even better version would be this:
DataTable FillDataTable(string sql, CommandType commandType, params OdbcParameter[] parameters)
{
var dataTable = new DataTable();
using(var con = new OdbcConnection(ConnectionString))
{
using(var command = new OdbcCommand(sql, con))
{
command.CommandType = commandType;
command.Parameters.AddRange(parameters);
using(var dataAdapter = new OdbcDataAdapter(SQLCommand))
{
dataAdapter.Fill(dataTable);
}
}
}
return dataTable;
}
If you want to improve that even further, You can have a look at my GitHub ADONETHelper project - There I have a single private method for Execute, and the methods for filling data tables, filling data sets, execute non query etc' all use this single method.
would you please try this instead
declare #row int
set #row=0;
select * from
(
select SUM(#row,1) as my____row_num,
cities.cityid as CityID,
cities.cityname as CityName,
cities.countryid as CountryID,
cities.countryname as CountryName ,
'1' as my____data_row_created , '1' as my____data_row_updated from cities) //i did not understand the meaning of this
where (my____row_num BETWEEN 100 AND 200 )
backEnd
ExcuteCommand(Sql)
{
<AddThis>ConnectionString= ConfigurationManager.ConnectionStrings["YourDataBaseLocation_OR_theConnectionCreatedViaProperties"].Connectionstring;</AddThis>
DataTable dt = new DataTable();
<deleteThis> OdbcCommand SQLCommand = new OdbcCommand(Sql);</deletethis>
//You Need to add the connection you have used it and Odbc
//Command.CommandType= CommandType.StoredProcedure();
OdbcConnection Con = new OdbcConnection(ConnectionString);
<AddThis>OdbcCommand SqlCommand = new OdbcCommand(Sql,Con);</AddThis>
try
{
Con.Open();
SQLCommand.Connection = Con;
OdbcDataAdapter da = new OdbcDataAdapter(SQLCommand);
da.Fill(dt);
<add this > SQLCommand.ExecuteNonQuery();</Add this>
Con.Close();
<delete> Con.Dispose();</delete>
}
catch
{
try
{
Con.Close();
}
catch (Exception e) { }
throw (e);
}
return dt;
}

Eclipselink JPA criteria format select date

I'm developing a web app with Spring 4 MVC and EclipseLink with MySQL. I'm currently stucked with a criteria query to get results with a date field. I have the following code:
CriteriaBuilder criteriaBuilder = entityManager().getCriteriaBuilder();
CriteriaQuery<Tuple> query = criteriaBuilder.createTupleQuery();
Root<SsiCheque> fromSsiCheque = query.from(SsiCheque.class);
List<Predicate> predicates = new ArrayList<Predicate>();
if(parameters.containsKey("cheNumero")){
System.out.println("Param " + parameters.get("cheNumero"));
predicates.add(criteriaBuilder.like(fromSsiCheque.<String>get("cheNumero"), "%" + parameters.get("cheNumero") + "%"));
}
if(parameters.containsKey("cheFechas")){
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String[] fechas = parameters.get("cheFechas").split(" - ");
try {
predicates.add(criteriaBuilder.between(fromSsiCheque.<Date>get("cheFecha"), formatter.parse(fechas[0]), formatter.parse(fechas[1])));
} catch (ParseException e) {
e.printStackTrace();
}
}
if(parameters.containsKey("cheReceptor")){
predicates.add(criteriaBuilder.like(fromSsiCheque.<String>get("cheReceptor"), "%" + parameters.get("cheReceptor") + "%" ));
}
query.multiselect(fromSsiCheque.get("cheId"), fromSsiCheque.get("cheNumero"),
fromSsiCheque.get("cheReceptor"), fromSsiCheque.get("cheMonto"),
criteriaBuilder.function("DATE_FORMAT",
String.class, fromSsiCheque.<Date>get("cheFecha"),
criteriaBuilder.literal("'%d/%m/%Y'")).alias("cheFecha"), fromSsiCheque.get("cheConcepto"))
.where(predicates.toArray(new Predicate[]{}));
TypedQuery<Tuple> typed = entityManager().createQuery(query);
The problem is in the multiselect section where I'm defining a date to be returned and formatted in dd/MM/yyyy with MySQL function DATE_FORMAT:
criteriaBuilder.function("DATE_FORMAT",
String.class, fromSsiCheque.<Date>get("cheFecha"),
criteriaBuilder.literal("'%d/%m/%Y'")).alias("cheFecha")
In some posts say the function is called TO_CHAR but it seems to be part of Oracle Database API.
The strange thing here is that I'm not getting errors (maybe I need to change logging level) but is not working.
Also I set the persistence.xml to show the generated sql and is as follows:
SELECT che_id, che_numero, che_receptor, che_monto, DATE_FORMAT(che_fecha, ?), che_concepto FROM ssi_cheque WHERE che_numero LIKE ?
bind => [%d/%m/%Y, %12%]
What Am I missing in my criteria query to show dates formatted?
Thanks
UPDATE
What I am getting from the database is 1416895200000 (the date field in milliseconds I guess).
Thanks

How to check for a null value in database

I am working in asp.net. I want that if the user has not uploaded his profile picture then he should be redirected to a 'profile picture uploading page'. For this we must check the database to see if that user's User_ID exists. If it doesn't exist in the database it means he has not uploaded yet. Otherwise it means he has already uploaded a picture and the page loads all of the user's information. I have a table for saving display picture:
Table: ProfilePic
Columns= ID DP User_ID
To check whether his user_id exists in the database, I use this code:
str = "select * from ProfilePic where Profile_ID=" + userid + ";";
cmd = new SqlCommand(str, con);
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
if (reader["Profile_ID"] != DBNull.Value)
{
LoadInfo();
LoadData();
}
else
{
Response.Redirect("DP.aspx");
}
But it's still saying "Invalid attempt to read when no data is present".
How do I resolve this problem?
You can check the reader for rows like the following example:
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
You say, "if that user's User_ID is not existing in the database it means he has not uploaded yet." That means when you run your query, it will either return a record or it won't. If it doesn't, looking for a null value in one of the fields is doomed to failure.
I see from Bjorn's answer that SqlDataReader has a HasRows property. Use it.
First of all, avoid:
Select * ...
when all you want to do is check if a particular value exists or not in a particular table. It has no benefit with respect to what about you're looking for and isn't good from a performance standpoint as well.
Now, coming to your question, there is no use of select * from. All you need to know is if a userID exists in a table or not. You see, this is a true or false scenario. Your query should also be designed to reflect this. So, essentially your query itself should return true or false and based on that you should be able to apply your business rules. You can also make use of just SELECT COUNT(). So here's the way I'd suggest to design your query:
string str = "SELECT CAST(COUNT(Profile_Id) AS bit) As 'DoesUserIDexist' FROM ProfilePic WHERE Profile_Id = 4";
You can also make use of:
string str = "SELECT COUNT(Profile_Id) As 'DoesUserIDexist' FROM ProfilePic WHERE Profile_Id = 4";
Also, its always a good practice to make use of try catch when you need to read from the database.
Essentially, your code can simplified so much as to this:
string query = "SELECT CAST(COUNT(Profile_Id) AS bit) As 'DoesUserIDexist' FROM ProfilePic WHERE Profile_Id = 4";
cmd = new SqlCommand(query, con);
try
{
SqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
LoadInfo();
LoadData();
}
else
{
Response.Redirect("DP.aspx");
}
}
catch
{
//Your exception handling mechanism here
}
finally
{
//Dispose your ADO.NET related objects here
}

SQL WHERE LIKE clause in JSF managed bean

Hi i have this managed bean where it makes MySQL queries, the problem here is the SQL statement makes a '=' condition instead of 'LIKE'
Here is the code in my managed bean.
Connection con = ds.getConnection();
try{
if (con == null) {
throw new SQLException("Can't get database connection");
}
}
finally {
PreparedStatement ps = con.prepareStatement(
"SELECT * FROM Clients WHERE Machine LIKE '53'");
//get customer data from database
ResultSet result = ps.executeQuery();
con.close();
List list;
list = new ArrayList();
while (result.next()) {
Customer cust = new Customer();
cust.setMachine(result.getLong("Machine"));
cust.setCompany(result.getString("Company"));
cust.setContact(result.getString("Contact"));
cust.setPhone(result.getLong("Phone"));
cust.setEmail(result.getString("Email"));
//store all data into a List
list.add(cust);
}
return list;
Here the SELECT command does not pull all the numbers in 'Machine' column which is like 53, but if i enter a whole value, such as the complete number (53544) in place of 53 then the result is pulled up. I am confused !!
Also if i replace the above select statement with SELECT * FROM Clients the entire database is stored in list. Any ideas ?
Use wildcards:
Like '%53%'
...means everything that contains '53'.
Like '%53' - it ends with 53
LIKE '53%' - it starts with 53
You can also use _ if You want to replace a single character.
You can find a descriptipn HERE
You sql query should be
"SELECT * FROM Clients WHERE Machine LIKE '%53%'