i get an error of
"This SqlTransaction has completed; it is no longer"
while multiple insert in a single table
mclDb.trans = mclDb.mCon.BeginTransaction();
try
{
foreach (DataGridViewRow dgvRow in dgvDetail.Rows) // get rows in details
{
ht.Clear();
string dtlPoCode = dgvRow.Cells[2].Value.ToString();
if (poCode == dtlPoCode) // check if po code matches
{
ht.Add("dtlPoCode", dtlPoCode);
ht.Add("dtlPoLine", dgvRow.Cells[3].Value.ToString());
ht.Add("dtlwhouse", dgvRow.Cells[12].Value.ToString());
ht.Add("dtlSkuCode", dgvRow.Cells[4].Value.ToString());
ht.Add("dtlUom", dgvRow.Cells[6].Value.ToString());
ht.Add("dtlmrQty", dgvRow.Cells[7].Value.ToString());
ht.Add("dtlBCode", dgvRow.Cells[10].Value.ToString());
ht.Add("dtlBExp", dgvRow.Cells[11].Value.ToString());
ht.Add("dtlBin", dgvRow.Cells[9].Value.ToString());
ht.Add("custPoCode", custPoCode);
ht.Add("grnCode", grnCode);
ht.Add("refCode", refCode);
mclDb.IUD(ht);
}
}
MessageBox.Show("Transaction Complete");
mclDb.trans.Commit();
}
catch (Exception error)
{
MessageBox.Show(error.Message, "Error Encountered", MessageBoxButtons.OK, MessageBoxIcon.Error); mclDb.trans.Rollback();
}
here is my IUD method
public void IUD(Hashtable ht)
{
try
{
Connect();
string cmd = "";
cmd = mStatements.getQuery(ht);
mAdptr = new SqlDataAdapter(cmd,mCon);
ds = new DataSet();
mAdptr.Fill(ds);
}
catch (Exception Ex)
{
throw new Exception(Ex.Message);
}
}
and my getquery method
public string getQuery(Hashtable ht)
{
StringBuilder qry = new StringBuilder();
qry.Append(" Insert into mTable values ");
qry.Append(" ('" + ht["custPoCode"] + "','" + ht["dtlPoCode"] + "', ");
qry.Append(" " + ht["dtlPoLine"] + ",'" + ht["dtlwhouse"] + "', ");
qry.Append(" '" + ht["dtlSkuCode"] + "','" + ht["dtlUom"] + "', ");
qry.Append(" " + ht["dtlmrQty"] + ",'" + ht["grnCode"] + "', ");
qry.Append(" '" + ht["refCode"] + "','" + ht["dtlBCode"] + "', ");
qry.Append(" '" + ht["dtlBExp"] + "','" + ht["dtlBin"] + "', ");
qry.Append(" '" + ht["dtlmrQty"] + "','' ) ");
return qry.ToString();
}
the number of rows to be inserted in the table will depend on how many rows are selected in dgvDetail (which is a datagridview)
any suggestions in how to use sqltransaction on my codes ?
tia
Related
I'm trying to enter data into the database from a DataGridView. I have 3 columns that contain Date.
When I try to insert to database I get the error:
Conversion failed when converting date and/or time from character string
With this I format the columns that show the date:
private void Import()
{
if (textBox4.Text.Trim() != string.Empty)
{
try
{
DataTable dt = GetDataTable(textBox4.Text);
dataGridView2.DataSource = dt.DefaultView;
dataGridView2.Columns[6].DefaultCellStyle.Format = "dd/mm/yyyy";
dataGridView2.Columns[8].DefaultCellStyle.Format = "dd/mm/yyyy";
dataGridView2.Columns[15].DefaultCellStyle.Format = "dd/mm/yyyy";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
With this part, I enter the data in the database from a DatagridView:
string constring = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
SqlConnection con = new SqlConnection(constring);
if (con.State == ConnectionState.Closed)
con.Open();
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
try
{
SqlCommand sqlCmd = new SqlCommand("insert into abonament (nr, serie, cui, client, sim, data_inst, activare, data_exp, telefon, nr_activat, nr_zile, ob, tip_client, email, datacurenta1, semnatura) values ('" + dataGridView1.Rows[i].Cells[0].Value + "','" + dataGridView1.Rows[i].Cells[1].Value + "','" + dataGridView1.Rows[i].Cells[2].Value + "','" + dataGridView1.Rows[i].Cells[3].Value + "','" + dataGridView1.Rows[i].Cells[4].Value + "','" + dataGridView1.Rows[i].Cells[5].Value + "','" + dataGridView1.Rows[i].Cells[6].Value + "','" + dataGridView1.Rows[i].Cells[7].Value + "','" + dataGridView1.Rows[i].Cells[8].Value + "','" + dataGridView1.Rows[i].Cells[9].Value + "','" + dataGridView1.Rows[i].Cells[10].Value + "','" + dataGridView1.Rows[i].Cells[11].Value + "','" + dataGridView1.Rows[i].Cells[12].Value + "','" + dataGridView1.Rows[i].Cells[13].Value + "','" + dataGridView1.Rows[i].Cells[14].Value + "','" + dataGridView1.Rows[i].Cells[15].Value + "')", con);
sqlCmd.ExecuteNonQuery();
MessageBox.Show("ok");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "error");
}
}
this was my solution
for (int i = 0; i < dataGridView2.RowCount; i++)
{
DateTime d1 = Convert.ToDateTime(dataGridView2.Rows[i].Cells[6].Value.ToString());
string format = "s";
DateTime d2 = Convert.ToDateTime(dataGridView2.Rows[i].Cells[8].Value.ToString());
DateTime d3 = Convert.ToDateTime(dataGridView2.Rows[i].Cells[15].Value.ToString());
try
{
SqlCommand sqlCmd = new SqlCommand("insert into abonament (nr, serie, cui, client, sim, data_inst, activare, data_exp, telefon, nr_activat, nr_zile, ob, tip_client, email, datacurenta1, semnatura) values ( #nr, #serie, #cui, #client, #sim, #data_inst, #activare, #data_exp, #telefon, #nr_activat, #nr_zile, #ob, #tip_client, #email, #datacurenta1, #semnatura)", con);
sqlCmd.Parameters.AddWithValue("#mode", "Add");
sqlCmd.Parameters.AddWithValue("#id", 0);
sqlCmd.Parameters.AddWithValue("#nr ", dataGridView2.Rows[i].Cells[1].Value);
sqlCmd.Parameters.AddWithValue("#serie ", dataGridView2.Rows[i].Cells[2].Value);
sqlCmd.Parameters.AddWithValue("#cui ", dataGridView2.Rows[i].Cells[3].Value);
sqlCmd.Parameters.AddWithValue("#client ", dataGridView2.Rows[i].Cells[4].Value);
sqlCmd.Parameters.AddWithValue("#sim ", dataGridView2.Rows[i].Cells[5].Value);
sqlCmd.Parameters.AddWithValue("#data_inst ", d1.Date.ToString(format));
sqlCmd.Parameters.AddWithValue("#activare ", dataGridView2.Rows[i].Cells[7].Value);
sqlCmd.Parameters.AddWithValue("#data_exp ", d2);
sqlCmd.Parameters.AddWithValue("#telefon ", dataGridView2.Rows[i].Cells[9].Value);
sqlCmd.Parameters.AddWithValue("#nr_activat ", dataGridView2.Rows[i].Cells[10].Value);
sqlCmd.Parameters.AddWithValue("#nr_zile ", dataGridView2.Rows[i].Cells[11].Value);
sqlCmd.Parameters.AddWithValue("#ob ", dataGridView2.Rows[i].Cells[12].Value);
sqlCmd.Parameters.AddWithValue("#tip_client ", dataGridView2.Rows[i].Cells[13].Value);
sqlCmd.Parameters.AddWithValue("#email ", dataGridView2.Rows[i].Cells[14].Value);
sqlCmd.Parameters.AddWithValue("#datacurenta1 ", d3);
sqlCmd.Parameters.AddWithValue("#semnatura ", dataGridView2.Rows[i].Cells[16].Value);
sqlCmd.ExecuteNonQuery();
}
I was trying to use this code two run two commands in one connection, which I couldn't do, here is my code:
using (SqlConnection connection = new SqlConnection(""))
{
string query = "SELECT DISTINCT quatro, tres FROM todos_cp ORDER BY quatro, tres ";
using (SqlCommand RetriveCommand = new SqlCommand(query, conn))
{
conn.Open();
SqlDataReader reader = RetriveCommand.ExecuteReader();
while (reader.Read())
{
string coluna = reader.GetString(reader.GetOrdinal("quatro"));
string coluna1 = reader.GetString(reader.GetOrdinal("tres"));
Boolean ElementDisplayed;
try
{
}
catch (NoSuchElementException i)
{
ElementDisplayed = false;
GDataPicker();
for (int x = 0; x < dataGridView1.Rows.Count; x++)
{
string query2 = #"INSERT INTO table_teste1(Rua, CodigoPostal, Distrito, Concelho, Freguesia, GPS) VALUES(" + "'" + dataGridView1.Rows[x].Cells["Rua"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["Código Postal"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["Distrito"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["Concelho"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["Freguesia"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["GPS"].Value + "');";
for (int x = 0; x < dataGridView1.Rows.Count; x++)
{
string query2 = #"INSERT INTO table_teste1 (Rua, CodigoPostal,Distrito,Concelho,Freguesia,GPS ) VALUES (" + "'" + dataGridView1.Rows[x].Cells["Rua"].Value + "', " + "'" + dataGridView1.Rows[x].Cells["Código Postal"].Value + "', "+ "'" + dataGridView1.Rows[x].Cells["Distrito"].Value + "', "+ "'" + dataGridView1.Rows[x].Cells["Concelho"].Value + "', "+ "'" + dataGridView1.Rows[x].Cells["Freguesia"].Value + "', "+ "'" + dataGridView1.Rows[x].Cells["GPS"].Value + "');";
using(SqlCommand InsertCommand = new SqlCommand(query2,connection))
{
InsertCommand.CommandText = query2;
InsertCommand.ExecuteNonQuery();
}
}
}
}
}
conn.Close();
}
}
My problem is most likely in the lines where I do:
InsertCommand.CommandText = query2;
InsertCommand.ExecuteNonQuery();
And says i already have one datareader.
Help would be really appreciated, thanks in advance!
Append you second command in "query2". As it is inline query Sql will consider that as two different query (Append after semicolon) and will execute in the same connection
After importing values into the SQLite, I try to extract the values of one graphic by selecting a query, but I get the following error:
SQL logic error or missing database
no such function: year
This is my insert query:
string addDat = "";
if (splittedValues[3] != "")
{
addDat += "INSERT INTO hyddnev (Station, Dat, Vkol) values (" + resultStation + ", '" + splittedValues[1] + "-01-" + (int.Parse(splittedValues[2])<10?"0":"") + splittedValues[2] + "', " + splittedValues[3] + ");";
}
if (splittedValues[4] != "")
{
addDat += "INSERT INTO hyddnev (Station, Dat, Vkol) values (" + resultStation + ", '" + splittedValues[1] + "-02-" + splittedValues[2] + "', " + splittedValues[4] + ");";
}
if (splittedValues[5] != "")
{
addDat += "INSERT INTO hyddnev (Station, Dat, Vkol) values (" + resultStation + ", '" + splittedValues[1] + "-03-" + splittedValues[2] + "', " + splittedValues[5] + ");";
}
if (splittedValues[6] != "")
{
addDat += "INSERT INTO hyddnev (Station, Dat, Vkol) values (" + resultStation + ", '" + splittedValues[1] + "-04-" + splittedValues[2] + "', " + splittedValues[6] + ");";
}
if (splittedValues[7] != "")
{
addDat += "INSERT INTO hyddnev (Station, Dat, Vkol) values (" + resultStation + ", '" + splittedValues[1] + "-05-" + splittedValues[2] + "', " + splittedValues[7] + ");";
}
if (splittedValues[8] != "")
{
addDat += "INSERT INTO hyddnev (Station, Dat, Vkol) values (" + resultStation + ", '" + splittedValues[1] + "-06-" + splittedValues[2] + "', " + splittedValues[8] + ");";
}
if (splittedValues[9] != "")
{
addDat += "INSERT INTO hyddnev (Station, Dat, Vkol) values (" + resultStation + ", '" + splittedValues[1] + "-07-" + splittedValues[2] + "', " + splittedValues[9] + ");";
}
if (splittedValues[10] != "")
{
addDat += "INSERT INTO hyddnev (Station, Dat, Vkol) values (" + resultStation + ", '" + splittedValues[1] + "-08-" + splittedValues[2] + "', " + splittedValues[10] + ");";
}
if (splittedValues[11] != "")
{
addDat += "INSERT INTO hyddnev (Station, Dat, Vkol) values (" + resultStation + ", '" + splittedValues[1] + "-09-" + splittedValues[2] + "', " + splittedValues[11] + ");";
}
if (splittedValues[12] != "")
{
addDat += "INSERT INTO hyddnev (Station, Dat, Vkol) values (" + resultStation + ", '" + splittedValues[1] + "-10-" + splittedValues[2] + "', " + splittedValues[12] + ");";
}
if (splittedValues[13] != "")
{
addDat += "INSERT INTO hyddnev (Station, Dat, Vkol) values (" + resultStation + ", '" + splittedValues[1] + "-11-" + splittedValues[2] + "', " + splittedValues[13] + ");";
}
if (splittedValues[14] != "")
{
addDat += "INSERT INTO hyddnev (Station, Dat, Vkol) values (" + resultStation + ", '" + splittedValues[1] + "-12-" + splittedValues[2] + "', " + splittedValues[14] + ");";
}
With splittedValues[1] I insert Year, from 01 to 12 is months and splittedValues[2] is days.
Now I want to get values from SQLite:
private void loadButton_Click(object sender, EventArgs e)
{
string command4 = "select vkol from hyddnev where station='"
+ comboBox1.SelectedItem.ToString() + "' and year(Dat) = '"
+ comboBox2.SelectedItem.ToString() + "' order by Dat";
var StartDate = comboBox2.Text;
var EndDate = comboBox2.Text;
SQLiteCommand sqlComm;
sqlComm = new SQLiteCommand("begin", Connection);
sqlComm.ExecuteNonQuery();
SQLiteDataAdapter insertDat = new SQLiteDataAdapter(command4, Connection);
DataTable dt = new DataTable();
insertDat.Fill(dt);
string s2 = "";
int i = 0;
int startYear2 = 0;
int.TryParse(StartDate, out startYear2);
DateTime dtStart2 = new DateTime(startYear2, 01, 01);
chart1.Series["Avg"].XValueType = ChartValueType.DateTime;
chart1.ChartAreas[0].AxisX.LabelStyle.Format = "yyyy-MM-dd";
chart1.ChartAreas[0].AxisX.Interval = 1;
chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Days;
chart1.ChartAreas[0].AxisX.IntervalOffset = 1;
chart1.Series["Avg"].MarkerSize = 10;
foreach (DataRow row in dt.Rows)
{
chart1.Series["Avg"].Points.AddXY(dtStart2.AddDays(i), row.ItemArray[0]);
i++;
string rowz = string.Format("Avg Q - {0}" + Environment.NewLine, row.ItemArray[0]);
s2 += "" + rowz;
}
How can I fix this code? I think my problem is from select query?
Can I take some example how to get year? Because in combobox2 I select only year, I do not have months and days...
Thank you..
First time post as I'm a bit stuck here.
I am using this code to return some rows from a SQL Server database:
public static SqlDataReader SQLSelect(string sqlcommand, string[,] parameters, int length)
{
try
{
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
conn.Open();
SqlDataReader reader;
SqlCommand cmd = new SqlCommand(sqlcommand, conn);
var allLength = parameters.Length;
for (int i = 0; i < parameters.Length - length; i++)
{
string paramid = parameters[i, 0];
if (paramid == "#date" || paramid == "#Date" || paramid == "#DATE")
{
string paramvalue = parameters[i, 1];
DateTime date = Convert.ToDateTime(paramvalue);
paramvalue = date.ToString("yyyy-MM-dd HH':'mm':'ss");
cmd.Parameters.Add(new SqlParameter(paramid, paramvalue));
}
else
{
string paramvalue = parameters[i, 1];
cmd.Parameters.Add(new SqlParameter(paramid, paramvalue));
}
}
cmd.CommandType = CommandType.StoredProcedure;
reader = cmd.ExecuteReader();
return reader;
}
catch
{
return null;
}
}
This function is called like so
string[,] parameters = new string[1, 2] { { "#studentid", studentid } };
SqlDataReader reader = Common.SQLSelect(Common.tblstudentprogressselectforprinting, parameters, 1);
now all runs fine except the reader only contains 13 rows of data where as the actual query being
exec sp_tblstudentprogress_selectforprinting #studentid=N'87'
as an example, returns 91 rows.
I'm at a loss as to why this is the case. Only thing I have noticed is when using SQL Server profiler, running the query from SQL Server, there is a RPC: Started and Completed, as for running from withing my web app, there is only an RPC: Started.
Any thoughts on this?
EDIT:
here is how I enumerate the reader
protected void btnPrint_Click(object sender, EventArgs e)
{
string[,] parameters = new string[1, 2] { { "#studentid", studentid } };
SqlDataReader reader = Common.SQLSelect(Common.tblstudentprogressselectforprinting, parameters, 1);
string firstname = txtFirstName.Text;
string lastname = txtLastName.Text;
int i=0;
string[] heading1 = new string[reader.FieldCount];
string[] heading2 = new string[reader.FieldCount];
string[] log = new string[reader.FieldCount];
try
{
while (reader.Read())
{
heading1[i] = "Progress Log for: Block: " + reader["block"].ToString() + " Lesson: " + reader["lesson"].ToString();
heading2[i] = "";
log[i] =
/*"PROGRESS LOG for " + reader["firstname"].ToString() + " " + reader["lastname"].ToString() + " Printed on " + DateTime.Today.ToShortDateString() + Environment.NewLine +*/
Environment.NewLine +
"Teacher: " + reader["teacher"].ToString() + Environment.NewLine +
"Date: " + reader["date"].ToString() + Environment.NewLine +
"Year: " + reader["year"].ToString() + Environment.NewLine +
"Block: " + reader["block"].ToString() + Environment.NewLine +
"Lesson: " + reader["lesson"].ToString() + Environment.NewLine +
"Warm Up: " + reader["warmup"].ToString() + Environment.NewLine +
"Range: " + reader["range"].ToString() + Environment.NewLine +
"Technique Sheet: " + reader["techniquesheet"].ToString() + Environment.NewLine +
"Technique Other: " + reader["techniqueother"].ToString() + Environment.NewLine +
Environment.NewLine +
"Notes: " + reader["notes"].ToString() + Environment.NewLine +
Environment.NewLine +
"Mark: " + reader["mark"].ToString()+ Environment.NewLine ;
i++;
}
}
catch
{
}
finally
{
if (Common.conn != null)
{
Common.conn.Close();
}
}
Common.PDFCreateProgressLog("Progress log for: " + firstname + " " + lastname, "Progress log for: " + firstname + " " + lastname, "PDF_" + firstname + " " + lastname + "-" + DateTime.Today.ToString("yyyy-MM-dd") + ".pdf", "Progress log for: " + firstname + " " + lastname, log, heading1, heading2);
}
You are confusing the meaning of the FieldCount property. It identifies the number of Columns, not the number of Rows. You cannot determine the total number of rows from a streaming source like a Reader, without enumerating all of the rows first (at least once, anyway).
So you will need to extend your arrays each time (lists might be easier for this) you read a row from the Reader and test the Reader to se when there are no more rows.
I'm trying to find out why tweetinvi streaming library is getting stuck when it's getting too much tweets from the followers, that I add with the function AddFollow(). In this function I'm putting 600 followers using a list that I create. Each of these tweets that I receive on my application go directly to a database but in at a uncertain time the application just stops bringing tweets and it doesn't show any error or exception in the debugging mode. The program it's in C# and I'm using visual studio 2012
Here is my code:
public void getTweets()
{
string[] sports = new string[] { "NFL" };
long[] list1 = critter_connex(sports);
int cont = 0;
DateTime pastDate = DateTime.MinValue;
string tweetType = "";
int id = 0;
using (var webClient = new WebClient())
{
webClient.Proxy = WebRequest.DefaultWebProxy;
webClient.Credentials = System.Net.CredentialCache.DefaultCredentials; ;
webClient.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
webClient.Headers["User-Agent"] = "MOZILLA/5.0 (WINDOWS NT 6.1; WOW64) APPLEWEBKIT/537.1 (KHTML, LIKE GECKO) CHROME/21.0.1180.75 SAFARI/537.1";
//using app key NECESITO VER TWEETS3
var credentials = TwitterCredentials.CreateCredentials("XXXXX", "XXXXX", "XXXXX", "XXXXX");
try
{
TwitterCredentials.ExecuteOperationWithCredentials(credentials, () =>
{
cont++;
var filteredStream = Stream.CreateFilteredStream();
for (int i = 0; i < list1.Length; i++)
{
filteredStream.AddFollow(list1[i]);
}
try
{
filteredStream.MatchingTweetReceived += (sender, arg) =>
{
try
{
if (conn.State.ToString() == "Closed")
{
conn.Open();
}
MySqlCommand command = new MySqlCommand();
MySqlDataReader reader;
command.Connection = conn;
command.CommandText = "SELECT sportName, specTeam FROM twitter_userids where userId = " + arg.Tweet.Creator.Id.ToString() + "";
command.Prepare();
reader = command.ExecuteReader();
try
{
if (reader.Read())
{
tweet.setSport(reader.GetString(0));
tweet.setTeam(reader.GetString(1));
}
}
finally
{
reader.Close();
conn.Close();
}
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
Console.WriteLine(ex.Message);
}
try
{
cont++;
if (cont == 10)
{
filteredStream.StopStream();
DateTime date = DateTime.Now;
getTweets();
}
if (tweetType == "Tweet")
{
if (pastDate > arg.Tweet.CreatedAt)
{
filteredStream.StopStream();
DateTime date = DateTime.Now;
getTweets();
}
}
if (arg.Tweet.IsRetweet)
{
tweet.setUser_name(arg.Tweet.RetweetedTweet.Creator.ScreenName);
tweet.setText(arg.Tweet.RetweetedTweet.Text);
tweet.setPublish_date(arg.Tweet.RetweetedTweet.CreatedAt);
tweet.setRetweet_date(arg.Tweet.CreatedAt);
tweetType = "Retweet";
tweet.setState("Retweet");
tweet_text = tweet.getText();
Console.WriteLine(tweet.getUser_name());
Console.WriteLine(tweet.getText());
string rt_final_date = tweet.getPublish_date().ToString("yyyy-MM-dd HH:mm:ss");
string rt_date = tweet.getRetweet_date().ToString("yyyy-MM-dd HH:mm:ss");
Console.WriteLine(rt_final_date);
Console.WriteLine(rt_date);
Console.WriteLine(tweet.getSport());
Console.WriteLine(tweet.getTeam());
Console.WriteLine("Retweet");
Console.WriteLine("\n");
if (tweet_text.IndexOf("http://") > -1)
{
int index = tweet_text.IndexOf("http://");
tweet.setLink(tweet_text.Substring(index));
if (tweet.getLink().IndexOf(" ") > -1)
{
int index2 = tweet.getLink().IndexOf(" ");
tweet.setLink(tweet.getLink().Substring(0, index2));
}
tweet.setText(tweet_text.Replace(tweet.getLink(), ""));
}
else
if (tweet_text.IndexOf("https://") > -1)
{
int index = tweet_text.IndexOf("https://");
tweet.setLink(tweet_text.Substring(index));
if (tweet.getLink().IndexOf(" ") > -1)
{
int index2 = tweet.getLink().IndexOf(" ");
tweet.setLink(tweet.getLink().Substring(0, index2));
}
tweet.setText(tweet_text.Replace(tweet.getLink(), ""));
}
MySqlCommand insert_rt = conn.CreateCommand();
if (tweet.getLink() != "")
{
insert_rt.CommandText = "INSERT INTO TABLE (user_name, tweet_text, tweet_link, tweet_date, tweet_sport, tweet_type, tweet_team, isFilter) SELECT * FROM (SELECT '" + tweet.getUser_name() + "', '" +
tweet.getText().Replace("'", "") + "', '" + tweet.getLink().Replace("'", "") + "', '" + rt_final_date + "', '" + tweet.getSport() + "', '" + tweet.getState() + "', '" + tweet.getTeam() + "', 0 ) AS tmp " +
"WHERE NOT EXISTS (SELECT tweet_text FROM (select tweet_text from TABLE order by tweet_id desc limit 50 ) as t WHERE t.tweet_text = '" + tweet.getText().Replace("'", "") + "' LIMIT 50) LIMIT 1";
}
else
{
insert_rt.CommandText = "INSERT INTO TABLE (user_name, tweet_text, tweet_date, tweet_sport, tweet_type, tweet_team, isFilter) SELECT * FROM (SELECT '" + tweet.getUser_name() + "', '" +
tweet.getText().Replace("'", "") + "', '" + rt_final_date + "', '" + tweet.getSport() + "', '" + tweet.getState() + "', '" + tweet.getTeam() + "', 0 ) AS tmp " +
"WHERE NOT EXISTS (SELECT tweet_text FROM (select tweet_text from TABLE order by tweet_id desc limit 50 ) as t WHERE t.tweet_text = '" + tweet.getText().Replace("'", "") + "' LIMIT 50) LIMIT 1";
}
conn.Open();
id = insert_rt.ExecuteNonQuery();
conn.Close();
tweet.setLink("");
}
else
{
tweet.setUser_name(arg.Tweet.Creator.ScreenName);
tweet.setText(arg.Tweet.Text);
pastDate = arg.Tweet.CreatedAt;
tweet.setPublish_date(arg.Tweet.CreatedAt);
tweetType = "Tweet";
tweet.setState("Tweet");
tweet_text = tweet.getText();
Console.WriteLine(tweet.getUser_name());
Console.WriteLine(tweet.getText());
string final_date = tweet.getPublish_date().ToString("yyyy-MM-dd HH:mm:ss");
Console.WriteLine(final_date);
Console.WriteLine(tweet.getSport());
Console.WriteLine(tweet.getTeam());
Console.WriteLine(tweet.getState());
Console.WriteLine("\n");
if (tweet_text.IndexOf("http://") > -1)
{
int index = tweet_text.IndexOf("http://");
tweet.setLink(tweet_text.Substring(index));
if (tweet.getLink().IndexOf(" ") > -1)
{
int index2 = tweet.getLink().IndexOf(" ");
tweet.setLink(tweet.getLink().Substring(0, index2));
}
tweet.setText(tweet_text.Replace(tweet.getLink(), ""));
}
else
if (tweet_text.IndexOf("https://") > -1)
{
int index = tweet_text.IndexOf("https://");
tweet.setLink(tweet_text.Substring(index));
if (tweet.getLink().IndexOf(" ") > -1)
{
int index2 = tweet.getLink().IndexOf(" ");
tweet.setLink(tweet.getLink().Substring(0, index2));
}
tweet.setText(tweet_text.Replace(tweet.getLink(), ""));
}
MySqlCommand insert_t = conn.CreateCommand();
if (tweet.getLink() != "")
{
insert_t.CommandText = "INSERT INTO TABLE (user_name, tweet_text, tweet_link, tweet_date, tweet_sport, tweet_type, tweet_team, isFilter) SELECT * FROM ( SELECT '" + tweet.getUser_name() + "', '" +
tweet.getText().Replace("'", "") + "', '" + tweet.getLink().Replace("'", "") + "', '" + final_date + "', '" + tweet.getSport() + "', '" + tweet.getState() + "', '" + tweet.getTeam() + "', 0 ) AS tmp " +
"WHERE NOT EXISTS (SELECT tweet_text FROM (select tweet_text from TABLE order by tweet_id desc limit 50 ) as t WHERE t.tweet_text = '" + tweet.getText().Replace("'", "") + "') LIMIT 1";
}
else
{
insert_t.CommandText = "INSERT INTO TABLE (user_name, tweet_text, tweet_date, tweet_sport, tweet_type, tweet_team, isFilter) SELECT * FROM ( SELECT '" + tweet.getUser_name() + "', '" +
tweet.getText().Replace("'", "") + "', '" + final_date + "', '" + tweet.getSport() + "', '" + tweet.getState() + "', '" + tweet.getTeam() + "', 0 ) AS tmp " +
"WHERE NOT EXISTS (SELECT tweet_text FROM (select tweet_text from TABLE order by tweet_id desc limit 50 ) as t WHERE t.tweet_text = '" + tweet.getText().Replace("'", "") + "') LIMIT 1";
}
conn.Open();
id = insert_t.ExecuteNonQuery();
conn.Close();
tweet.setLink("");
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
};
filteredStream.StartStreamMatchingAllConditions();
}
catch (Exception ex)
{
Console.WriteLine(ex);
getTweets();
}
tweet_text = "";
getTweets();
filteredStream.StartStreamMatchingAllConditions();
});
getTweets();
}
catch (Exception ex)
{
getTweets();
Console.WriteLine(ex);
}
getTweets();
}
}
Thanks.
Have you tried to register to the StreamStopped event and check that everything is working correcly?
filteredStream.StreamStopped += (sender, args) =>
{
Console.WriteLine(args.DisconnectMessage.Reason);
if (args.Exception != null)
{
Console.WriteLine(args.Exception);
}
};