format string with int64 value - c#

i have a web service in which training number is assigning as per my database
there is a line
dates + "1"; this lines add 1 in date
like 27012017 will become 270120171
then i convert this into int64
newid = Convert.ToInt64(dates);
but now i want to add trainer id in this
so i updated my line with this
dates ="00"+trainerid +"-"+ dates + "1";
newid = Convert.ToInt64(dates);
the error is coming input string is not in correct format,
i know this is because of the addition of +"-"+
but i want to store the data in this format only
and my whole portion look like
DateTime dt = DateTime.Now;
string dates = dt.ToString();
dates = dates.Replace("-", "");
dates = dates.Substring(0, 8);
SqlCommand cmdbill = new SqlCommand("select top 1 * from listmybill where bill_id like #trid order by bill_id desc", con);
con.Open();
cmdbill.Parameters.AddWithValue("#trid", "%" + dates + "%");
SqlDataReader dr = cmdbill.ExecuteReader();
while (dr.Read())
{
value = dr["bill_id"].ToString();
}
con.Close();
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdbill);
DataTable dat = new DataTable();
da.Fill(dat);
if (dat.Rows.Count > 0)
{
newid = Convert.ToInt64(value);
newid = newid + 1;
}
else
{
dates ="00"+trainerid +"-"+ dates + "1";
newid = Convert.ToInt64(dates);
}
con.Close();
what should i do here,
i want to enter the data like 001-270120171
and if i convert toInt64 into string,
there can be problem when a row found in the table
if (dat.Rows.Count > 0)
{
newid = Convert.ToInt64(value);
newid = newid + 1;
}
what i need to do now?
i want to store this into my database

I hardly think you will be doing mathematical calculations on this training number string. I suggest that you convert the int in your database into a varchar using alter statement. Then you you will be able to store the training number in whichever format you like.

You can change new id to string and do the following
if (dat.Rows.Count > 0)
{
newid = Convert.ToString(Convert.ToInt64(value)+1);
}
else
{
newid="00"+trainerid +"-"+ dates + "1";
}

Related

Get COUNT of data at the current hour of system date

I have a table of data in Access
DateTimeLog has date/time datatype while the other rest are string.
I need to get the total number of row of data at the last hour of system date with specified ModelLog. But I could not think of a correct structure of the query using MS Access as I am very new to MS Access.
Below shows how I insert the data:
DateTime now = DateTime.Now;
var today = now.ToString("g");
DateTime d = DateTime.Parse(today);
const string sql = #"INSERT INTO timer(DateTimeLog, ShiftLog, CTLog, WorkcellLog, ModelLog, StationLog)VALUES(#d, #shift, #ct, #wc, #wm, #ws)";
OleDbCommand cmd = new OleDbCommand(sql, connection);
cmd.Parameters.Add("#d", OleDbType.DBTimeStamp).Value = d;
cmd.Parameters.Add("#shift", OleDbType.VarChar).Value = shiftlb.Text;
cmd.Parameters.Add("#ct", OleDbType.VarChar).Value = timerlb.Text;
cmd.Parameters.Add("#wc", OleDbType.VarChar).Value = wclb.Text;
cmd.Parameters.Add("#wm", OleDbType.VarChar).Value = mlb.Text;
cmd.Parameters.Add("#ws", OleDbType.VarChar).Value = slb.Text;
try
{}
catch(exception e)
{}
Ok, so you clearly know how to run a database query with parameters, you just need to run this query as ExecuteScalar, casting the result to an int
SELECT COUNT(*) FROM timer WHERE dateTimeLog >= #d
And then set your d parameter to an hour ago
cmd.Parameters.Add("#d", OleDbType.Date).Value = DateTime.Now.AddHours(-1);
Side note I would recommend not round tripping via string just to cut the seconds off a time. Instead consider:
var d = DateTime.Now;
d = d.AddTicks( -(d.Ticks % (60*TimeSpan.TicksPerSecond)));
Or maybe
var d = DateTime.Now;
d = d.AddMilliseconds(-d.Milliseconds).AddSeconds(-d.Seconds);
I found out another way of getting the number of data within the same hour. Create two new columns, HourID and TodayDate both represent current hour in 24hours format and today's date respectively. Insert the data accordingly.
Getting count of data:
const string sql = #"SELECT COUNT(*) FROM timer WHERE HourID = #h AND TodayDate = #td AND ModelLog = #m";
OleDbCommand cmd = new OleDbCommand(sql, connection);
cmd.Parameters.Add("#h", OleDbType.VarWChar).Value = DateTime.Now.ToString("%H");
cmd.Parameters.Add("#td", OleDbType.VarWChar).Value = DateTime.Now.ToShortDateString();
cmd.Parameters.Add("#m", OleDbType.VarWChar).Value = mlb.Text;

Invalid column name on adapter fill

I am getting a System.Data.SqlClient.SqlException with additional information of an Invalid column name Jun on Fill function while I am entering 19-jun-2016 from the datetimePicker and here is a Jun is a month but it taking it as a column.
ReportForm.cs
public void MakeDailyReport(string givenDate, DataGridView view)
{
con.Open();
cmd = new SqlCommand("SELECT Date FROM FinalSales where Date = #datePicker", con);
cmd.Parameters.AddWithValue("#datePicker", givenDate);
cmd.ExecuteNonQuery();
DateTime dateObject = (DateTime)cmd.ExecuteScalar();
string dateObjectstring = Convert.ToString(dateObject.ToShortDateString());
string givenDateString = Convert.ToString(givenDate);
if (dateObjectstring == givenDateString)
{
DataTable dt = new DataTable();
adapt = new SqlDataAdapter("SELECT Date FROM FinalSales where Date = " + givenDate + "", con);
if (adapt != null)
{
adapt.Fill(dt);
view.DataSource = dt;
}
else
{
MessageBox.Show("No Record found againts that date");
con.Close();
}
}
else
{
con.Close();
}
}
Don't use string concatenation to build your query but sql parameters with the correct type. That will also prevent you from sql injection and other possible issues (like this one).
adapt = new SqlDataAdapter("SELECT [Date] FROM FinalSales where [Date] = #givenDate", con);
var dateParameter = adapt.SelectCommand.Parameters.Add("#givenDate", SqlDbType.DateTime);
dateParameter.Value = dateTimePicker.Value.Date; // not string but the correct type DateTime
Note that i've also used dateTimePicker.Value.Date to ignore the time portion.

CSV - Import file to a Sql database through code

I need to load data from text file/csv file to a SQL Server database. I used the code shown below to load data and is loading to the database the problem is the data in second column may contain space but I use space for separate the column data.
i.e.
200007 XXXX Check XXXX yyy 50
200013 YYYY Check ZZZZ yyy 50
200022 nnnn 25Mg 30 Tabs
200042 mmmm 30 Mg 30 Tabs
I need to store the first ID number in the first column and the remaining text in second column:
string str = Properties.Settings.Default.con;
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand();
try
{
cmd.Connection = con;
con.Open();
cmd.CommandText = "IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='TEMP_AUTO' AND xtype='U')" +
"CREATE TABLE TEMP_AUTO (" +
"ID varChar(10) NULL," +
"NAME varChar(50) NULL," +
"DATE TIMESTAMP NULL," +
")";
cmd.ExecuteNonQuery();
string query1 = "INSERT INTO [dbo].[TEMP_AUTO]([ID],[NAME]) VALUES (#num1, #num2)";
cmd.CommandText = query1;
string[] allLines = File.ReadAllLines(txtFilePath.Text);
for (int i = 0; i < allLines.Length; i++)
{
cmd.Parameters.Clear();
string[] items = allLines[i].Split(new char[] { ' ' });
cmd.Parameters.AddWithValue("#num1", items[0]);
cmd.Parameters.AddWithValue("#num2", items[1]);
cmd.ExecuteNonQuery();
}
MessageBox.Show("Successfully saved your data");
}
finally
{
cmd.Dispose();
con.Close();
}
A possible solution might be this:
string[] allLines = {
"200007 XXXX Check XXXX yyy 50",
"200013 YYYY Check ZZZZ yyy 50",
"200015 ",
"2541111"
};
for (int i = 0; i < allLines.Length; i++)
{
string param1 = null;
string param2 = null;
int spaceIndex = allLines[i].IndexOf(' ');
if (spaceIndex > 0)
{
param1 = allLines[i].Substring(0, spaceIndex);
if (spaceIndex < allLines[i].Length - 1)
{
param2 = allLines[i].Substring(spaceIndex + 1, allLines[i].Length-1 - spaceIndex);
}
}
else
{
param1 = allLines[i];
}
Console.WriteLine("param1:{0} param2:{1}", param1, param2);
}
Use SSIS to map this file as long as it has a standard structure to SQL Table.
Is this a one time thing? Have you tried getting the data organized in Excel then using the SSMS import tool to bring it in? If you right click on the Database then Tasks > Import Data the wizard will appear when given the option to choose the source, choose Excel. Flat files is an option but if you can format it in Excel first that tends to work better.
As you click through you can adjust the column types and where the breaks are, much like importing into Excel itself.
Use the String.Split(Char[], Int32) method to split on the first occurrence of ' ' only. Eg
string[] items = allLines[i].Split(new char[] { ' ' }, 2);
Refs: MSDN and previous relevant question
Use the below code.
using (StreamReader sr = File.OpenText("txtFile.txt")) // Mention the path,if the file is not in application folder.
{
string str = String.Empty;<br/>
while ((str = sr.ReadLine()) != null)
{
string[] item = str.Split(' ');
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand();
string query1 = "INSERT INTO [dbo].[TEMP_AUTO]([ID],[NAME]) VALUES ('" + item[0] + "', '" + item[1] + "')";
// Do remain part<br/>
}
}

C# How to do loop variable for query (where)

Please help I can't understand about variable for query by when in SQL command. -> get value and do loop again and again (get and change) sorry I'm not good english
This code :
var ee = 0;
var command = new SqlCommand("SELECT Values,date FROM db_db where date ='" + ee ", connection);
var reader = command.ExecuteReader();
var dt = 8;
for (int i = 0; i <= dt; i++)
{
dataGridView1.Columns.Add("A", starttime.AddMonths(i).ToString("MM", seCultureInfo) + "/" + starttime.AddMonths(i).ToString("yyyy", seCultureInfo));
mm = "1";
}
while (reader.Read())
{
var value = reader.GetDecimal(2);
// var column = new DataGridViewTextBoxColumn();
// column.HeaderText = header.ToString();
// this.dataGridView1.Columns.Add(column);
if (dataGridView1.RowCount < 2)
{
this.dataGridView1.Rows.Add();
}
this.dataGridView1.Rows[0].Cells[columnIndex].Value = value;
/* This --------------->*/ ee++;
columnIndex++;
}
Look at "ee". I want to keep value "ee" and bring it back in query command by new "ee".
Last date of value was wrong it's correct at 07/2015
If I got your question correctly , you want to reuse the SQL but increasing the 'ee' variable .
It is impossible .
If your business logic is about query based on different date, You have to build the SQL command again and again .

SQL SELECT query not retrieving rows from a simple Access database

The DayDate column in the database is of type DateTime & I'm passing a string formulated using a DateTimePicker in a form. The reader.HasRows always returns false!! I don't know what I'm doing wrong. Any help would be appreciated. The code that I used is below.
if (!this.con.IsConnected())
{
this.con.Connect();
}
this.cmd = new OleDbCommand("SELECT DayNo FROM [Calendar] WHERE DayDate = " + date + "", this.con.conObj());
this.reader = cmd.ExecuteReader();
this.reader.Read();
int dayNo;
if (this.reader.HasRows)
{
dayNo = int.Parse(reader[0].ToString());
}
else
{
throw new InfoException("The system could not locate the date in the system");
}
The problem is your comparing a Date value to a DateTime so in essence you could possibly be comparing values like this:
DayDate = "2011-12-18 14:22:54"
Date = "2011-12-18 00:00:00"
You need to truncate the time part from your DB dates, try something like this:
"SELECT DayNo FROM [Calendar] WHERE dateadd(dd, 0, datediff(dd, 0, DayDate)) = " + date
Or if using SQL Server 2008 you can do:
"SELECT DayNo FROM [Calendar] WHERE cast(DayDate As Date) = " + date

Categories