I have a text file contains around 8000 lines.
Each lines must have 90 characters.
Each lines contain different blocks so I have to use substring for each blocks.
For Eg.
xx-xxxxxxxxx-xx-xxxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxx
I use Substring(x,x) to get each block in for loop.
Some of lines have do not have 122 characters,
For Eg. xx-xxxxxxxxx-xx-xxxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxx-xxxxx
so i would like to skip those lines and proceed for others. I don't understand the proper use of String.Skip function in C#.
Here is my code.
public void getext()
{
// bool check = false;
MySqlConnectionStringBuilder con = new MySqlConnectionStringBuilder();
con.Server = "xxx";
con.UserID = "xxx";
con.Password = "xxx";
con.Database = "xxx";
MySqlConnection sqlcon = new MySqlConnection(con.ToString());
string padding = "";
try
{
sqlcon.Open();
//var watch = System.Diagnostics.Stopwatch.StartNew();
var path = "C:\\xxx\\xxx\\xxx\\1.txt";
var lines = File.ReadAllLines(path);
for (var i = 0; i < lines.Length; i += 1)
{
string str = lines[i].ToString();
string code, control1, actype, control2, filler, control3, sponsor,
control4, amtdate, control5;
code = str.Substring(0, 2);
control1 = str.Substring(2, 9);
actype = str.Substring(11, 2);
control2 = str.Substring(13, 18);
filler = str.Substring(31, 40);
control3 = str.Substring(74, 16);
sponsor = str.Substring(90, 20);
MySqlCommand cmd = new MySqlCommand("addext", sqlcon);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("code", MySqlDbType.VarChar).Value = code;
cmd.Parameters.Add("control1", MySqlDbType.VarChar).Value = control1;
cmd.Parameters.Add("actype", MySqlDbType.VarChar).Value = actype;
cmd.Parameters.Add("control2", MySqlDbType.VarChar).Value = control2;
cmd.Parameters.Add("filler", MySqlDbType.VarChar).Value = filler;
cmd.Parameters.Add("control3", MySqlDbType.VarChar).Value = control3;
cmd.Parameters.Add("sponsor", MySqlDbType.VarChar).Value = sponsor;
cmd.ExecuteNonQuery();
//sqlcon.Close();
label1.Visible = true;
//sqlcon.Close();
//watch.Stop();
//var elapsedMs = watch.Elapsed.TotalMinutes;
label1.Text = "success";
// sqlcon.Close();
}
sqlcon.Close();
}
catch (Exception ex)
{
label1.Visible = true;
label1.Text = "fail" + ex.ToString();
}
}
If you want to skip a number/line within your loop you can use
continue;
example:
for (var i = 0; i < lines.Length; i += 1)
{
string str = lines[i];
if (str.length != 122) // We only want to Work with lines which are 122 chars long.
continue;
DoWork(); // Insert you code here ;)
}
I believe you want to skip lines which are less than 122 characters? You can filter them out from your loop and process only the ones that have required length.
foreach(var str in lines.Where(x=>x.Length>=122))
{
string code, control1, actype, control2, filler, control3, sponsor,
control4, amtdate, control5;
code = str.Substring(0, 2);
// rest of your code
}
The Filter and Foreach approach would keep away the indices, increasing readability of the code
Related
Hi i am trying to create a validation that checks if its an Unsuccessful SQL Query - if no results are returned, it should catch this error and display a message on screen 'No record found for Client ID: [number]'
The query i currently have fetching the information is below.
protected void ClientSearchBtn_Click(object sender, EventArgs e)
{
//string ClientID = ClientIDTxt.Text;
//Database connection. Calls from web.config.
string MyConnectionString = ConfigurationManager.ConnectionStrings
["RCADSCONNECTION"].ConnectionString;
//SQL Connection
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = MyConnectionString;
//myConnection.Open();
//SQL string
try
{
SqlCommand cmd = new SqlCommand("SELECT CN.ClientID, CI.NNN, CN.GivenName1, CN.Surname, CI.DateOfBirth, CI.Gender FROM [RioOds].dbo.ClientIndex CI LEFT JOIN [RioOds].[dbo].[ClientName] CN ON CN.ClientID = CI.ClientID AND CN.AliasType = '1' AND CN.EndDate IS NULL WHERE CN.ClientID = #clientid", myConnection);
cmd.Parameters.Add("#clientid", SqlDbType.Int).Value = ClientIDTxt.Text;
myConnection.Open();
var reader = cmd.ExecuteReader();
StringBuilder sb = new StringBuilder();
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
if (i != 0)
{
sb.Append(" | ");
}
sb.Append(reader[i].ToString());
}
sb.AppendLine();
ClientIDCell.Text = reader[0].ToString();
NNNCell.Text = reader[1].ToString();
FirstNameCell.Text = reader[2].ToString();
SurnameCell.Text = reader[3].ToString();
DobCell.Text = reader[4].ToString();
GenderCell.Text = reader[5].ToString();
}
//Show the results table
queryResultsTable.Visible = true;
ResultsLabel.Text = sb.ToString();
submitButton.Enabled = true;
resultsButton.Enabled = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
myConnection.Close();
}
myConnection.Close();
}
I am unsure how to go by doing this. I do understand itll be an if statement but unsure how to compare an sql query return to being null.
reader.Read() returns true if there are more rows to read. First time only if it is false that means reader has no data.
if(!reader.Read())
//Your message
else
{
do
{
for (int i = 0; i < reader.FieldCount; i++)
{
if (i != 0)
{
sb.Append(" | ");
}
sb.Append(reader[i].ToString());
}
sb.AppendLine();
ClientIDCell.Text = reader[0].ToString();
NNNCell.Text = reader[1].ToString();
FirstNameCell.Text = reader[2].ToString();
SurnameCell.Text = reader[3].ToString();
DobCell.Text = reader[4].ToString();
GenderCell.Text = reader[5].ToString();
} while (reader.Read());
}
Another option is to check the property HasRows on reader. It's true when there is data in it.
if(!reader.HasRows)
//Your error message goes from here
else
//Do your stuff
I am creating a windows form application that generates timetable automatically. I am having a problem to write a query when a user select semester number from the dropdown(from 1-8) then what should I write in query? My Code is below.
private void button_generate_Click(object sender, EventArgs e)
{
SqlCommand com;
SqlConnection con = new SqlConnection("Data Source=MAJOR-DYNASTI;Initial Catalog=ESS;Integrated Security=True");
con.Open();
string a = comboBox_semester.SelectedText;
string str = "SELECT CourseName, TeacherName, RoomName FROM Course_teacher, RoomInfo where Semester= ORDER BY NEWID(); ";
com = new SqlCommand(str, con);
SqlDataReader reader = com.ExecuteReader();
if (reader.HasRows)
{
Random random = new Random();
var labels = new Label[] { label1, label2, label3, label4, label5, label6, label7, label8,label9,label10,label11,label12,label13,label14,label15,label16,
label17,label18,label19,label20,label21,label22,label23,label24,label25,label26,label27,label28,label29,label30,label31,
label32,label33,label34,label35,label36,label37,label38,label39,label40,label41,label42,label43,label44,label45,label46,label47,label48,
label49,label50};
label1.Text = ""; label2.Text = ""; label3.Text = ""; label4.Text = ""; label5.Text = ""; label6.Text = "";
label7.Text = "";label8.Text = "";label9.Text = "";label10.Text = "";label11.Text = "";label12.Text = "";label13.Text = "";label14.Text = "";label15.Text = "";label16.Text = "";
label17.Text = "";label18.Text = "";label19.Text = "";label20.Text = "";label21.Text = "";label22.Text = "";label23.Text = "";label24.Text = "";label25.Text = "";label26.Text = "";label27.Text = "";label28.Text = "";label29.Text = "";label30.Text = "";label31.Text = "";
label32.Text = ""; label33.Text = ""; label34.Text = ""; label35.Text = ""; label36.Text = ""; label37.Text = ""; label38.Text = ""; label39.Text = ""; label40.Text = ""; label41.Text = ""; label42.Text = ""; label43.Text = ""; label44.Text = ""; label45.Text = ""; label46.Text = ""; label47.Text = ""; label48.Text = "";
label49.Text = "";label50.Text = "";
if (
comboBox1.SelectedItem==null ||
comboBox2.SelectedItem==null ||
comboBox_semester.SelectedItem==null)
{
MessageBox.Show("Please Select Complete Detail");
}
else
{
while (reader.Read())
{
int randomNumber = random.Next(1, 50);
labels[randomNumber].Text = String.Format("{0},\r\n{1},\r\n{2}", reader["CourseName"], reader["TeacherName"], reader["RoomName"]);
}
}
}
I want query for these two lines.
string a = comboBox_semester.SelectedText;
string str = "SELECT CourseName, TeacherName, RoomName FROM Course_teacher, RoomInfo where Semester=(what should I need to write here) ORDER BY NEWID(););
Please Help
You need to put your variable a into your query like so:
string str = "SELECT CourseName, TeacherName, RoomName FROM Course_teacher, " +
"RoomInfo WHERE Semester = #Semester ORDER BY NEWID()";
com.Parameters.Add(new SqlParameter("Semester", a));
Just note that I cleaned up your query a little bit, and I introduced parameterized queries in case you're unfamiliar with them.
The best way to do this is going to look something like this:
"Where Semester = #Semester"
Then, on a following line, you add a Parameter to your SqlCommand object like so:
com.Parameters.AddWithValue("#Semester", a);
This lets the SQLCommand object know to substitute your variable (I've named it #Semester for now) with the value you have received from the user.
I have looked at the other questions with this title and I think the problem is something local with my code that I am missing.
The function that this button preforms is to calculate the points/rewards that a person earns based on the transaction total. For example, $10 = 1 point, 19=1 point, 20=2. 10 Points = 1 Rewards points, which is equal to a ten dollar credit.
My Code receives the title error message. I will include the entire function for completeness.
private void button1_Click(object sender, EventArgs e)
{
try{
string cs = #"server=localhost;userid=root;password=root;database=dockingbay94";
MySqlConnection conn;
//MySqlDataReader rdr = null;
using (conn = new MySqlConnection(cs));
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
string input = textBox2.Text;
MySqlCommand myCommand2 = conn.CreateCommand();
myCommand2.CommandText = "SELECT Points FROM members WHERE id = #input";
MySqlDataAdapter MyAdapter2 = new MySqlDataAdapter();
MyAdapter2.SelectCommand = myCommand2;
double transaction = Convert.ToDouble(textBox3.Text);
double tmp_transaction = Math.Floor(transaction);
string transaction_date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
double pointsbefore = (tmp_transaction / 10.0);
int currentpoints = Convert.ToInt32(pointsbefore);
int rewards = 0;
int oldpoints = 0;
string temp = "";
pointsbefore = Math.Floor(pointsbefore);
int new_points;
double tmp_rewards = 0.0;
double tmp_points;
int new_rewards;
oldpoints = (int)myCommand2.ExecuteScalar();
new_points = currentpoints + oldpoints;
tmp_points = new_points / 10;
int tmp_rewards2 = 0;
if (new_points > 10)
{
tmp_rewards = Math.Floor(tmp_points);
tmp_rewards2 = Convert.ToInt32(tmp_rewards);
}
else if (new_points == 10)
{
tmp_rewards2 = 1;
}
else
{
tmp_rewards2 = 0;
}
new_rewards = rewards + tmp_rewards2;
int points_left = 0;
if (new_points > 10)
{
for (int i = 10; i < new_points; i++)
{
points_left++;
}
}
else if (new_points == 10)
{
points_left = 0;
}
else if (new_points < 10)
{
for (int i = 0; i < new_points; i++)
{
points_left++;
}
}
string query = "UPDATE members Set Points=#Points, rewards_collected=#Rewards, transaction_total=#Transaction, transaction_date=#TransactionDate" + "WHERE id = #input;";
MySqlCommand cmdDataBase = new MySqlCommand(query, conn);
cmdDataBase.Parameters.Add("#input", SqlDbType.Int).Value = Convert.ToInt32(textBox2.Text);
cmdDataBase.Parameters.AddWithValue("#Points", new_points);
cmdDataBase.Parameters.AddWithValue("#Rewards", new_rewards);
cmdDataBase.Parameters.AddWithValue("#Transaction", textBox3.Text);
cmdDataBase.Parameters.AddWithValue("#TransationDate", transaction_date);
MySqlDataReader myReader2;
myReader2 = cmdDataBase.ExecuteReader();
MessageBox.Show("Data Updated");
if(conn.State == ConnectionState.Open){
conn.Close();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
I am not sure where the error could be. Probably not sending the right value.
Thanks
This line is wrong
using (conn = new MySqlConnection(cs));
Remove the semicolon and include everything that needs the MySqlConnection variable inside a {} block
using (MySqlConnection conn = new MySqlConnection(cs))
{
// No need to test if the connection is not open....
conn.Open();
.........
// Not needed (at least from your code above
// MySqlDataAdapter MyAdapter2 = new MySqlDataAdapter();
// MyAdapter2.SelectCommand = myCommand2;
... calcs follow here
// Attention here, if the query returns null (no input match) this line will throw
oldpoints = (int)myCommand2.ExecuteScalar();
.... other calcs here
MySqlCommand cmdDataBase = new MySqlCommand(query, conn);
cmdDataBase.Parameters.Add("#input", SqlDbType.Int).Value = Convert.ToInt32(textBox2.Text);
cmdDataBase.Parameters.AddWithValue("#Points", new_points);
cmdDataBase.Parameters.AddWithValue("#Rewards", new_rewards);
cmdDataBase.Parameters.AddWithValue("#Transaction", textBox3.Text);
cmdDataBase.Parameters.AddWithValue("#TransationDate", transaction_date);
// Use ExecuteNonQuery for INSERT/UPDATE/DELETE and other DDL calla
cmdDataBase.ExecuteNonQuery();
// Not needed
// MySqlDataReader myReader2;
// myReader2 = cmdDataBase.ExecuteReader();
// Not needed, the using block will close and dispose the connection
if(conn.State == ConnectionState.Open)
conn.Close();
}
There is also another error in the final query. Missing a space between #TransactionDate parameter and the WHERE clause. In cases where a long SQL command text is needed I find very useful the verbatim string line character continuation #
string query = #"UPDATE members Set Points=#Points, rewards_collected=#Rewards,
transaction_total=#Transaction, transaction_date=#TransactionDate
WHERE id = #input;";
I am trying to split a string of values actually individually and trying to send it into database via Store procedure but i can't figure out that how ?
String to be Split: "2013-03-31,1299,2013-03-31,1099,9888, 0"
CODE:
public bool SqlInsert(String parametersString)
{
//It should be split here
SqlConnection sqlCon = new SqlConnection(conStr);
SqlCommand sqlCom = new SqlCommand("AddCoordinates", sqlCon);
sqlCom.CommandType = CommandType.StoredProcedure;
sqlCom.Parameters.Add("#AddedDateTime", SqlDbType.VarChar).Value = "";
sqlCom.Parameters.Add("#IMEI", SqlDbType.VarChar).Value = "";
sqlCom.Parameters.Add("#RecordedDateTime", SqlDbType.VarChar).Value = "";
sqlCom.Parameters.Add("#Latitude", SqlDbType.VarChar).Value = "";
sqlCom.Parameters.Add("#Longitude", SqlDbType.VarChar).Value = "";
sqlCom.Parameters.Add("#IsParking ", SqlDbType.Bit).Value = true;
try
{
sqlCon.Open();
int NoRows = (int)sqlCom.ExecuteNonQuery();
}
catch (Exception ex) { }
finally
{
sqlCon.Close();
}
return true;
}
Looks to me like it's just comma delimited, in which case try:
string[] parts = "2013-03-31,1299,2013-03-31,1099,9888, 0".Split(',');
However, that makes working with parts a bit awkward, so we can go a step further:
string[] fields = new string[] {"date","imei","recorded_date","lat","lon","is_parking"};
List<string,string> dict = Dictionary<string,string>();
for(var i = 0; i < parts.Length; i++) {
var key = fields[i];
var value = parts[i].Trim(); // You may or may not want to trim the value
dict.Add(key,value);
}
You can then pull the individual fields you want and convert them to the type you need, for example:
int imei = int.Parse(dict["imei"]);
Of course, I'm sidestepping a couple of issues like type conversion failure and disparities between parts and fields, but you get the general idea.
The approach mentioned by #Lloyd is the easiest one.Here is the code for your understanding.
string[] parts = "2013-03-31,1299,2013-03-31,1099,9888, 0".Split(',');
sqlCom.Parameters.Add("#AddedDateTime", SqlDbType.VarChar).Value = parts[0].ToString();
sqlCom.Parameters.Add("#IMEI", SqlDbType.VarChar).Value = parts[1].ToString();
sqlCom.Parameters.Add("#RecordedDateTime", SqlDbType.VarChar).Value = Convert.ToDateTime(parts[2].ToString());
sqlCom.Parameters.Add("#Latitude", SqlDbType.VarChar).Value = parts[3].ToString(); ;
sqlCom.Parameters.Add("#Longitude", SqlDbType.VarChar).Value = parts[4].ToString(); ;
sqlCom.Parameters.Add("#IsParking ", SqlDbType.Bit).Value = ((parts[5].ToString().Trim()).Equals("0"))? true: false;
Hope it helps!
MessageBox.Show(urls[m]);
of the code below it show 16 time like a,a,a,a,b,b,b,b,c,c,c,c,d,d,d,d how can i add 4 non duplicate to urls[m]. My code is purpose to swlwct url from data base to open on 4 different browser1 browser 2 .. but on browser show the same URL
namespace tabcontrolweb
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string MyConString = "SERVER=192.168.0.78;" +
"DATABASE=webboard;" +
"UID=aimja;" +
"PASSWORD=aimjawork;" +
"charset=utf8;";
MySqlConnection connection = new MySqlConnection(MyConString);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "SELECT urlwebboard FROM `listweb` WHERE `urlwebboard` IS NOT NULL AND ( `webbordkind` = 'เว็บท้องถิ่น' ) and `nourl`= 'n' order by province, amphore limit 4 ";
connection.Open();
Reader = command.ExecuteReader();
string[] urls = new string[4];
string thisrow = "";
string sumthisrow = "";
while (Reader.Read())
{
thisrow = "";
for (int i = 0; i < Reader.FieldCount; i++)
{
thisrow += Reader.GetValue(i).ToString();
System.IO.File.AppendAllText(#"C:\file.txt", thisrow + " " + Environment.NewLine);
sumthisrow = Reader.GetValue(i).ToString();
}
for (int m = 0; m < 4 ; m++)
{
urls[m] = sumthisrow;
MessageBox.Show(urls[m]);
}
webBrowser1.Navigate(new Uri(urls[0]));
webBrowser1.Dock = DockStyle.Fill;
webBrowser2.Navigate(new Uri(urls[1]));
webBrowser2.Dock = DockStyle.Fill;
webBrowser3.Navigate(new Uri(urls[2]));
webBrowser3.Dock = DockStyle.Fill;
webBrowser4.Navigate(new Uri(urls[3]));
webBrowser4.Dock = DockStyle.Fill;
}
connection.Close();
}
I can't understand this code:
for (int m = 0; m < 4 ; m++)
{
urls[m] = sumthisrow;
MessageBox.Show(urls[m]);
}
Why are you inserting in urls[m] the same value?
Bear in mind that in the previous loop the variable sumthisrow will keep only the last value just like:
sumthisrow = Reader.GetValue(Reader.FieldCount - 1).ToString();
EDIT: Also consider using a StringBuilder for creation of thisrow variable.
EDIT 2: Put your disposable objects into a using statement.