I am trying to build an application which searches all attributes step by step daily and monthly using the between statement. The daily queries run, but monthly dones't run.
The code:
if (libs.conn.con.State == ConnectionState.Closed) libs.conn.baglanti.Open();
string today = "select getdate()";
SqlCommand today1 = new SqlCommand(today, libs.conn.con);
string today2 = today1.ExecuteScalar().ToString();
string[] day = today2.Split(' ');
day[0] += " 00:00:00";
string dayy = (DateTime.Now.Day).ToString();
string month = (DateTime.Now.Month).ToString();
string year = (DateTime.Now.Year).ToString();
string[] combine = new string[] { "1." };
combine[0] += month + ".";
combine[0] += year + " ";
combine[0] += "00:00:00";
string totalmonth = "(SELECT SUM(para) FROM statistics where datee between '"+combine[0]+"' AND '"+today2+"')";
SqlCommand totalmoneymonthlyquery = new SqlCommand(totalmoneymonth, libs.conn.baglanti);
string totalmoneymonthlyresult = totalmoneymonthlyquery.ExecuteScalar().ToString();
textBox7.Text = totalmoneymonthlyresult.ToString();
use
combine[0]=today2
use first
you may get parameter error to pull data.
String.Format("{0:d/M/yyyy HH:mm:ss}", dt);
String.Format("{0:d/M/yyyy HH:mm:ss}", dt);
Related
I have mysql Database and i want to read data from there in my web application with for loop instead of foreach loop.
MySqlConnection conn = new MySqlConnection(connStr);
conn.Open();
string query = "SELECT * FROM survey ORDER BY datetime DESC";
MySqlCommand com = new MySqlCommand(query, conn);
com.CommandTimeout = 0;
MySqlDataAdapter da = new MySqlDataAdapter(com);
DataTable ds = new DataTable();
da.Fill(ds);
conn.Close();
foreach (DataRow item in ds.Rows)
{
string unique = item.ItemArray[4].ToString();
var sur = db2.VoipSurveys.Where(a => a.UniqueId == unique).SingleOrDefault();
if (sur == null)
{
VoipSurvey vs = new VoipSurvey()
{
Date = Convert.ToDateTime(item.ItemArray[1]),
Point = Convert.ToInt32(item.ItemArray[2]),
CallerId = item.ItemArray[3].ToString(),
UniqueId = item.ItemArray[4].ToString(),
AgentNumber = item.ItemArray[5].ToString(),
AgentName = item.ItemArray[6].ToString(),
QueueNumber = item.ItemArray[7].ToString()
};
db2.VoipSurveys.Add(vs);
db2.SaveChanges();
}
}
I need reading data from specific index like reading data in mysql table from this Date until now. and i think my problem would be solved with for loop
You can use a DataView RowFilter also:
// Create a DataView
DataView dv = new DataView(dt);
dv.RowFilter = " (Date >= #" +
Dateyouwanttouse +
"# And Date <= #" +
DateTime.Now +
"# ) ";
Simply do this:
foreach (DataRowView rowView in dv)
{
DataRow row = rowView.Row;
// Do something //
}
For several days I've been struggling to display data from the table in DataSet. When I do not put a condition in the WHERE, it displays the complete table, but only the rows in the table that meet the condition are required. If there are suggestions for a quicker view. Thanks a lot.
myConnectionString = pwput;
MySqlConnectionconpara = new MySql.Data.MySqlClient.MySqlConnection();
conpara.ConnectionString = myConnec DataSetionString;
try
{
conpara.Open();
if (conpara.State == ConnectionState.Open)
{
string waccoun1 = wnalog1.ToString();
string waccoun2 = wnalog2.ToString();
stringnupita = "SELECT * FROM book WHERE year=wyear AND account >=
waccount1 AND account <= waccount1";
MySqlCommandcmdnal = new MySqlCommand(nupita,conpara);
MySqlCommand(nupita,conpara);cmdnal.Parameters.AddWithValue("#year",
wyear);
MySqlDataAdapte radda = new MySqlataAdapter(cmdnal);
MySqlCommandBuildercbb = new MySqlCommandBuilder(adda);
DataSet dsd = new DataSet();
adda.Fill(dsd, "book");
conpara.Close();
if (dsd != null)
{
dataGridView1.DataSource = dsd;
dataGridView1.DataMember = "book";
Font = new System.Drawing.Font("Arial Unicode", 7);
dataGridView1.Font = Font;
{
You need to use parameters like so:
...
stringnupita = "SELECT * FROM book WHERE year=#year AND account >=
#waccount1 AND account <= #waccount2";
MySqlCommand(nupita,conpara);cmdnal.Parameters.AddWithValue("#year",
wyear);
MySqlCommand(nupita,conpara);cmdnal.Parameters.AddWithValue("#waccount1",
waccount1);
MySqlCommand(nupita,conpara);cmdnal.Parameters.AddWithValue("#waccount2",
waccount2);
...
I'm creating appointments like
Appointment appointment = new Appointment(service);
appointment.Subject = m.Subject;
appointment.Start = m.StartTime;
appointment.End = m.EndTime;
appointment.StartTimeZone = TimeZoneInfo.Utc;
appointment.EndTimeZone = TimeZoneInfo.Utc;
....
appointment.Save(folder, SendInvitationsMode.SendToNone);
I can then retrieve the CalIdVal
My system lists out appointments for users. I get this using
GetUserAvailabilityResults results = service.GetUserAvailability(attendees, tw, AvailabilityData.FreeBusyAndSuggestions);
I'd like to filter out the appointment created above.
But this list doesn't contain any IDs so I can't see how.
Any advice appreciated
You need to set the FreeBusyViewType in you GetUserAvailability to Detailed https://learn.microsoft.com/en-us/dotnet/api/microsoft.exchange.webservices.data.freebusyviewtype?view=exchange-ews-api then you should get back a list of HexEntryId's for the appointments which you then can convert to EWSId so you can bind/filter eg
DateTime StartTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 0:00"));
DateTime EndTime = StartTime.AddDays(1);
TimeWindow tmTimeWindow = new TimeWindow(StartTime, EndTime);
AvailabilityOptions aoOptions = new AvailabilityOptions();
aoOptions.RequestedFreeBusyView = Microsoft.Exchange.WebServices.Data.FreeBusyViewType.DetailedMerged;
aoOptions.MeetingDuration = 30;
List<AttendeeInfo> atAttendeeList = new List<AttendeeInfo>();
atAttendeeList.Add(new AttendeeInfo("user#domain.com"));
GetUserAvailabilityResults avResponse = service.GetUserAvailability(atAttendeeList, tmTimeWindow, AvailabilityData.FreeBusy, aoOptions);
Int32 atnCnt = 0;
foreach (AttendeeAvailability avail in avResponse.AttendeesAvailability)
{
Console.WriteLine(atAttendeeList[atnCnt].SmtpAddress);
Int32 mc = 0;
var merged = avail.MergedFreeBusyStatus;
while (StartTime < EndTime)
{
Console.WriteLine(StartTime.ToString() + " " + merged[mc]);
mc++;
StartTime = StartTime.AddMinutes(30);
}
foreach (Microsoft.Exchange.WebServices.Data.CalendarEvent calendarItem in avail.CalendarEvents)
{
Console.WriteLine("Free/busy status: " + calendarItem.FreeBusyStatus);
Console.WriteLine("Start time: " + calendarItem.StartTime);
Console.WriteLine("End time: " + calendarItem.EndTime);
var convertedId = (AlternateId)service.ConvertId(new AlternateId(IdFormat.HexEntryId, calendarItem.Details.StoreId, "someemail#domain.com"), IdFormat.EwsId);
var apt = Appointment.Bind(service, new ItemId(convertedId.UniqueId));
}
atnCnt++;
}
I am doing a query to the database prepared statement but its just not coming out right.
i get this error when I print my statement.
com.mysql.jdbc.JDBC42PreparedStatement#157b62f9: SELECT * FROM 2015-wind WHERE TimeStamp BETWEEN '2015-01-01' AND '2015-01-25' AND ConnectingArea IN (** NOT SPECIFIED **)
10YAT-APG--L (I print my string and it give me an output).
Anybody knows whats going on here ?
public List<Wind2015> getResultsWind(String beginDate1, String endDate1, String[] connectingAreas1) throws Exception{
int count = 0;
List<Wind2015> myWind2015s = new ArrayList<>();
SimpleDateFormat readFormat = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy",
Locale.ENGLISH);
Date date2 = readFormat.parse(beginDate1);
Date date3 = readFormat.parse(endDate1);
String beginDate = new SimpleDateFormat("yyyy-MM-dd").format(date2);
String endDate = new SimpleDateFormat("yyyy-MM-dd").format(date3);
ArrayList<String> connectingArea = new ArrayList<>(Arrays.asList(connectingAreas1));
StringBuilder inputs = new StringBuilder();
for (int i = 0; i < connectingArea.size(); i++) {
if (i < connectingArea.size()-1) {
inputs.append("?,");
} else {
inputs.append("?");
}
}
String connectingAreaInputs = inputs.toString();
Connection connection = null;
PreparedStatement prepareStatement = null;
ResultSet myRs = null;
System.out.println(connectingAreaInputs);
try {
connection = getConnection();
String sql = "SELECT * FROM `2015-wind` WHERE `TimeStamp` BETWEEN ? AND ? AND `ConnectingArea` IN ("+ connectingAreaInputs +")";
prepareStatement = connection.prepareStatement(sql);
prepareStatement.setString(count+=1,beginDate);
prepareStatement.setString(count+=1, endDate);
System.out.println(prepareStatement);
for (String string : connectingArea) {
System.out.println(string);
count+=1;
prepareStatement.setString(count, string);
}
myRs = prepareStatement.executeQuery();
Wind2015 wind2015 = null;
while (myRs.next()) {
String timeStamp = myRs.getString("Timestamp");
String connectingArea1 = myRs.getString("ConnectingArea");
String value = myRs.getString("ActualWindEnergy");
wind2015 = new Wind2015(timeStamp, value, connectingArea1);
myWind2015s.add(wind2015);
}
return myWind2015s;
} finally {
close(connection, prepareStatement, myRs);
}
}
You're printing the prepared statement with this line:
System.out.println(prepareStatement);
before you assign value(s) to the dynamic placeholders in the IN (...) expression, so they're (correctly) displaying as "not [yet] specified".
Move the print statement to after the for loop that it currently sits before.
This has been driving me crazy and I'm sure it's something simple. I'm getting a 'values must contain at least one element' error from server when I try to input a reservation from the table that comes up. It's all running ok. No matter if I use quotes in the VALUES section or plus(+)symbols or quotes over the separating commas I get different error messages. When I put quotes over table_num I get and error telling me that you cant insert CHAR into INTEGER. When I remove quotes I get error telling me -
Severe: java.sql.SQLSyntaxErrorException: Column 'TABLE_NUM' is either not in any table in the FROM list or appears within a join specification etc. Could anyone tell me what is going on? Here's the jsp code. Thanks in advance.
<%
int tableNum = 0;
String firstName = null;
String lastName = null;
String Address = null;
int Phone = 0;
java.sql.Date date = null;
int People = 0;
if (request.getParameter("table_num")!=null){
tableNum = Integer.parseInt(request.getParameter("table_num"));
}
if (request.getParameter("first")!=null){
firstName = request.getParameter("first");
}
if (request.getParameter("last")!=null){
lastName = request.getParameter("last");
}
if (request.getParameter("address")!=null){
Address = request.getParameter("address");
}
if (request.getParameter("phone")!=null){
Phone = Integer.parseInt(request.getParameter("phone"));
}
if (request.getParameter("date")!=null){
java.util.Date utilDate = new java.util.Date(request.getParameter("date"));
date = new java.sql.Date(utilDate.getTime());
}
if (request.getParameter("people")!=null){
People = Integer.parseInt(request.getParameter("people"));
}
if(tableNum != 0 && firstName != null && lastName != null && Address != null && Phone != 0 && date != null && People != 0){
String URL = "jdbc:derby://localhost:1527/Reservations";
String USERNAME= "johnpaul";
String PASSWORD= "purlease";
Connection myCon = null;
Statement ste = null;
PreparedStatement preparedStmt = null;
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
System.out.println("Connecting to DB...");
Connection con=DriverManager.getConnection("jdbc:derby://localhost:1527/Reservations","johnpaul", "purlease");
System.out.println("Connected successfuly");
System.out.println("Inserting records into table");
Statement st = con.createStatement();
String query = "INSERT INTO JOHNPAUL.CUSTOMER_RESERVATIONS(TABLE_NUM,FIRST_NAME,LAST_NAME,ADDRESS,TELEPHONE,DATE,NUMBER_IN_PARTY)VALUES(table_num,first,last,address,phone,date,people)";
st.executeUpdate (query);
System.out.println("Records inserted");
}catch(SQLException se){
se.printStackTrace();
}catch(ClassNotFoundException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
}
%>
Your problem appears to be here:
String query = "INSERT INTO JOHNPAUL.CUSTOMER_RESERVATIONS
(TABLE_NUM, FIRST_NAME,LAST_NAME,ADDRESS,TELEPHONE, DATE, NUMBER_IN_PARTY)
VALUES (table_num, first,last,address,phone,date,people)";
Two things here:
1. Escape your strings; and
2. Concatenate the values in your variables to the string.
String query = "INSERT INTO JOHNPAUL.CUSTOMER_RESERVATIONS
(TABLE_NUM, FIRST_NAME,LAST_NAME,ADDRESS,TELEPHONE, DATE, NUMBER_IN_PARTY)
VALUES (" + table_num + ", '" + first + "', '" + last + "', '" + address + "', " + phone + " , '" + date + "', " + people + ");";
You may have to verify the format that your database engine expects the date field.