I am getting this error while trying to connect my web site.
Unspecified error Description: An
unhandled exception occurred during
the execution of the current web
request. Please review the stack trace
for more information about the error
and where it originated in the code.
Exception Details:
System.Data.OleDb.OleDbException:
Unspecified error.
Maybe I am doing something wrong while opening and closing connections. I always get this error if 5-10 user enter same time to site. When a user enter site I am updating or inserting new records for statistics.
I am using db class for connect:
public OleDbConnection baglan()
{
OleDbConnection baglanti = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Server.MapPath("~/App_Data/manisaweb.mdb"));
baglanti.Open();
return (baglanti);
}
//********************************************************************
//Sql Sorgu Çalıştırma
public int cmd(string sqlcumle)
{
OleDbConnection baglan = this.baglan();
OleDbCommand sorgu = new OleDbCommand(sqlcumle, baglan);
int sonuc = 0;
try
{
sonuc = sorgu.ExecuteNonQuery();
}
catch (OleDbException ex)
{
throw new Exception(ex.Message + " (" + sqlcumle + ")");
}
finally
{
sorgu.Connection.Close();
}
return (sonuc);
}
//********************************************************************
//Kayıt Sayısı Bulma
public string GetDataCell(string sql)
{
DataTable table = GetDataTable(sql);
if (table.Rows.Count == 0)
return null;
return table.Rows[0][0].ToString();
}
//Kayıt Çekme
public DataRow GetDataRow(string sql)
{
DataTable table = GetDataTable(sql);
if (table.Rows.Count == 0) return null;
return table.Rows[0];
}
//DataTable ye veri çekme
public DataTable GetDataTable(string sql)
{
OleDbConnection baglan = this.baglan();
OleDbDataAdapter adapter = new OleDbDataAdapter(sql, baglan);
DataTable dt = new DataTable();
try
{
adapter.Fill(dt);
}
catch (OleDbException ex)
{
throw new Exception(ex.Message + " (" + sql + ")");
}
finally
{
adapter.Dispose();
baglan.Close();
}
return dt;
}
//Datasete veri çekme
public DataSet GetDataSet(string sql)
{
OleDbConnection baglan = this.baglan();
OleDbDataAdapter adapter = new OleDbDataAdapter(sql, baglan);
DataSet ds = new DataSet();
try
{
adapter.Fill(ds);
}
catch (OleDbException ex)
{
throw new Exception(ex.Message + " (" + sql + ")");
}
finally
{
ds.Dispose();
adapter.Dispose();
baglan.Close();
}
return ds;
}
And for STATISTICS in main.master.cs every page_load event
public void Istatistik()
{
string IpAdres = Request.ServerVariables["REMOTE_ADDR"].ToString();//Ip Adresini alıyoruz.
string Tarih = DateTime.Now.ToShortDateString();
lblOnlineZiyaretci.Text = Application["OnlineUsers"].ToString();//Online ziyaretçi
//Ogüne Ait Hit Bilgi Güncelleme
DataRow drHit = GetDataRow("Select * from SayacHit Where Tarih='" + Tarih + "'");
if (drHit == null)
{
//Bugüne ait kayıt yoksa bugunün ilk siftahını yap
cmd("Insert into SayacHit(Tarih,Tekil,Cogul) values('" + Tarih + "',1,1)");
}
else
{
string SayfaAdi = Page.ToString().Replace("_aspx", ".aspx").Remove(0, 4); //Sayfa adını alıyoruz.
if (SayfaAdi == "default.aspx")//Güncelleme işlemini sadece anasayfadaysa yapıyoruz
{
//Bugüne ait kayıt varsa Çoğulu 1 artırıyoruz.
cmd("Update SayacHit set Cogul=Cogul+1 Where Tarih='" + Tarih + "'");
}
//Tekil artımı için önce Ip kontrolü yapıyoruz.
DataRow drIpKontrol = GetDataRow("select * from SayacIp Where Ip='" + IpAdres + "'");
if (drIpKontrol == null)
{ //Eğer ip yoksa tekilide artırabiliriz. Ip kayıtlı ise artırma işlemi yapmıyoruz.
cmd("Update SayacHit set Tekil=Tekil+1 Where Tarih='" + Tarih + "'");
}
}
//Giren Kişinin IP sini Kaydetme
DataRow drIp = GetDataRow("Select * from SayacIp Where Ip='" + IpAdres + "'");
if (drIp == null)
{
cmd("Insert into SayacIp(Ip,Tarih) values('" + IpAdres + "','" + Tarih + "')");
}
//Ekrana Bilgileri Yazdırabiliriz
DataRow drSonuc = GetDataRow("Select * from SayacHit Where Tarih='" + Tarih + "'");
lblBugunTop.Text = drSonuc["Cogul"].ToString();
//lblBugunTekil.Text = drSonuc["Tekil"].ToString();
//Dün Bilgilerini Çekme
//DataRow drDun = GetDataRow("Select * from SayacHit Where Tarih='" + DateTime.Now.AddDays(-1).ToShortDateString() + "'");
DataRow drGenel = GetDataRow("Select SUM(Tekil) as Toplam from SayacHit");
//if (drDun != null)
//{
// lblDunTop.Text = drDun["Tekil"].ToString();
//}
//else
//{
// lblDunTop.Text = "0";
//}
lblGenelTop.Text = drGenel["Toplam"].ToString();
lblIPAdresi.Text = IpAdres;
}
And then there is 2 section in Default.aspx; it loads at the page load event for news and articles.
db veri = new db();
rptNews.DataSource = veri.GetDataTable("select top 5 KullaniciAdiSoyadi,Ozet,Baslik,Tarih,IcerikID,Icerik from Icerik a inner join Kullanici d on a.KullaniciID=d.KullaniciID where KategoriID = 1 and Durum = 1 Order by IcerikID Desc ");
rptNews.DataBind();
rptArticle.DataSource = veri.GetDataTable("select top 5 Ozet,Baslik,Tarih,IcerikID,Icerik from Icerik where KategoriID = 2 and Durum = 1 Order by IcerikID Desc ");
rptArticle.DataBind();
So there is so many UPDATE, INSERT and SELECT queries in every page load event. If this is my problem, is there another way of doing this?
It would help if you showed a bit more of the code. With this much information it could be anything. I'll take 2 guesses:
1) You have a limit of 5 connections, either on your Db or in ConnectionPooling
2) You forgot to close (Dispose) one or more Database objects
I would second Henk's #2 suggestion: failure to properly close database connections. If you are using DataSets or DataReaders, sending inline SQL or calling stored procedures, you must close the connections in code when you are through with them. If you don't close the connection, the number of available connections is gradually maxed out, and no new database requests can be made. It is only after enough users' sessions time out and the connections are released that other users can obtain a connection.
You have the exact symptom of unclosed connections: everything works fine for the first few users. But gradually, as more users log in, or as the original users move about the web app, opening ever more database connections, that everything locks up.
One way to diagnose this would be to use a database profiler tool (Profiler for SQL Server) to examine the database connections as they are opened and closed.
Related
not sure if stackoverflow is normally used for stuff like this but i'm looking for assistance in optimizing my code. I am running a method to query a count from a database which is fast and works fine. and a timer that is set to run this every 5 minutes. When i implement the timer in my main window after initialization it freezes when opening the window for 30+ seconds. It didn't do that before I added the timers. Any help optimizing this or tips on improving the way this works would be great!
Method that runs SQL query:
public string SQLDataTotalCalls()
{
DateTime dte = DateTime.Today;
string fixedStartDate = String.Format("{0:yyyy-MM-dd " + "05:00:00.000" + "}", dte);
string fixedEndDate = String.Format("{0:yyyy-MM-dd " + "05:00:00.000" + "}", dte.AddDays(1));
SqlConnection connection = null;
using (connection)
{
try
{
var dataSet = new DataSet();
connection = new SqlConnection("Data Source=QL1OADB1;Initial Catalog=OADB;User Id=;Password=");
connection.Open();
var command = new SqlCommand("SELECT COUNT(SOURCEID) AS 'MYCOUNT' "
+ "FROM [OADB].[oadb].[CmsCallHistory] "
+ "WHERE disposition = 2 and DISPSPLIT in (" + SkillNumber + ") AND SEGSTOP BETWEEN '" + fixedStartDate + "' and '" + fixedEndDate + "'",
connection)
{
CommandType = CommandType.Text
};
var dataAdapter = new SqlDataAdapter { SelectCommand = command };
dataAdapter.Fill(dataSet);
return dataSet.Tables[0].Rows[0]["MYCOUNT"].ToString();
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
finally
{
if (connection != null)
{
connection.Close();
}
}
}
}
Timer that triggers the method every 5 minutes:
public async Task RunPeriodicQueryTotalCalls()
{
TimeSpan interval = TimeSpan.FromMinutes(5);
while (true)
{
await Task.Delay(interval);
string result = await Task.Run((Func<string>)SQLDataTotalCalls);
TotalDailyCalls = result;
}
}
This is where i initialize the window. please note that I run these querys also when the application first launches before the timer runs otherwise the numbers will not post until it runs 5 minutes later:
public ScoreBoardBigViewWindow()
{
InitializeComponent();
string value = "Enter Skill Number Here";
if (Tmp.InputBox("New document", "New document name:", ref value) == System.Windows.Forms.DialogResult.OK)
{
SkillNumber = value;
}
TotalDailyLast7Days = SQLDataSevenPastCalls();
TotalDailyCalls = SQLDataTotalCalls();
TotalDailyAbandon = SQLDataAbandonCalls();
RunPeriodicQueryTotalCalls();
RunPeriodicQueryAbandonCalls();
}
If i remove RunPeriodicQueryTotalCalls(); and RunPeriodicQueryAbandonCalls(); then the performance issue goes away.
If stackoverflow is not the right place to ask this type of question please let me know and I'll reach out to other avenues for further assistance.
I have two tables, the first table is Course and this table contains three columns Course_ID, Name_of_course, DeptID; and the second table is Department and it has three columns DeptID, DepName, College.
I put a GridView to display the data that I will add it. But when I write the command to insert the data in both tables the data don't add. I used this command
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
GridViewRow r = GridView1.SelectedRow;
Dbclass db = new Dbclass();
string s = "";
DataTable dt = db.getTable(s);
ddcollege.SelectedValue = dt.Rows[0]["College"].ToString();
dddept.SelectedValue = dt.Rows[1]["DepName"].ToString();
tbid.Text = r.Cells[0].Text;
tbcourse_name.Text = r.Cells[1].Text;
lblid.Text = tbid.Text;
lberr.Text = "";
}
catch (Exception ex)
{
lberr.Text = ex.Message;
}
}
protected void btadd_Click(object sender, EventArgs e)
{
try
{
if (tbid.Text == "")
{
lberr.Text = "Please input course id";
return;
}
if (tbcourse_name.Text == "")
{
lberr.Text = "Please input course name";
return;
}
string s = "Insert into Course(Course_ID,Name_of_course) values ('" + tbid.Text + "','" + tbcourse_name.Text + "')";
s = "INSERT INTO Department (DepName,College,DeptID) VALUES ('"+dddept.SelectedValue+"','"+ddcollege.SelectedValue+"','"+tbdeptID.Text+"')";
Dbclass db = new Dbclass();
if (db.Run(s))
{
lberr.Text = "The data is added";
lblid.Text = tbid.Text;
}
else
{
lberr.Text = "The data is not added";
}
SqlDataSource1.DataBind();
GridView1.DataBind();
}
catch (Exception ex)
{
lberr.Text = ex.Message;
}
}
Here is the Dbclass code:
public class Dbclass
{
SqlConnection dbconn = new SqlConnection();
public Dbclass()
{
try
{
dbconn.ConnectionString = #"Data Source=Fingerprint.mssql.somee.com;Initial Catalog=fingerprint;Persist Security Info=True;User ID=Fingerprint_SQLLogin_1;Password=********";
dbconn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
//----- run insert, delete and update
public bool Run(String sql)
{
bool done= false;
try
{
SqlCommand cmd = new SqlCommand(sql,dbconn);
cmd.ExecuteNonQuery();
done= true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return done;
}
//----- run insert, delete and update
public DataTable getTable(String sql)
{
DataTable done = null;
try
{
SqlDataAdapter da = new SqlDataAdapter(sql, dbconn);
DataSet ds = new DataSet();
da.Fill(ds);
return ds.Tables[0];
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return done;
}
}
Thank you all
The main thing I can see is you are assigning two different things to your "s" variable.
At this point db.Run(s) the value is "Insert into Department etc" and you have lost the first sql string you assigned to "s"
Try:
string s = "Insert into Course(Course_ID,Name_of_course) values ('" + tbid.Text + "','" + tbcourse_name.Text + "')";
s += "INSERT INTO Department (DepName,College,DeptID) VALUES ('"+dddept.SelectedValue+"','"+ddcollege.SelectedValue+"','"+tbdeptID.Text+"')";
Notice the concatenation(+=). Otherwise as mentioned above using a stored procedure or entity framework would be a better approach. Also try to give your variables meaningful names. Instead of "s" use "insertIntoCourse" or something that describes what you are doing
When a value is inserted into a table(Table1) and and value has to be entered to into another table(Table2) on insertion of value to Table1, you can use triggers.
https://msdn.microsoft.com/en-IN/library/ms189799.aspx
"tbdeptID.Text" is giving you the department Id only right? You should be able to modify your first statement
string s = "Insert into Course(Course_ID,Name_of_course,) values ('" + tbid.Text + "','" + tbcourse_name.Text + "',)";
Please start running SQL Profiler, it is a good tool to see what is the actual query getting executed in server!
Good Day everyone. I'm new to this forum and I would like to ask help on my problem. I am currently creating a program where a user can perform queries themselves or in short terms like a query builder kind of application in c#.net
I'm using XAMPP and Visual Studio 2012.
I'm trying to create an SQLcommand from strings and try to execute it to fill my datagrid. However I'm getting the following error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'emp_code = 00802' at line 1
My String Query that I made was
SELECT * FROM emp_main WHERE emp_code = 00802
When i checked online on Mysql Syntax Checker there was no error on my syntax.
Here is my code on a Button Click Event
string SelStr = "SELECT * FROM " + tbTblName.Text.Trim().ToString() + " WHERE";
List<string> fildz = new List<string>();
List<string> oper= new List<string>();
List<string> valz = new List<string>();
foreach (Control ctrl in this.panel2.Controls)
{
if (ctrl.Name.Contains("tbField"))
{
fildz.Add(" " + ctrl.Text.ToString());
}
else if (ctrl.Name.Contains("tbOper"))
{
oper.Add(" " + ctrl.Text.ToString());
}
else if (ctrl.Name.Contains("tbVal"))
{
valz.Add(" " + ctrl.Text.ToString() + "AND");
}
}
string finalqry = "";
var results = fildz.Zip(oper, (x, y) => x + y).Zip(valz, (x, y) => x + y);
foreach (var item in results)
{
finalqry += item.ToString();
}
int inx = finalqry.LastIndexOf("AND");
MessageBox.Show( SelStr + finalqry.Substring(0,inx));
try
{
string xqry;
xqry = finalqry.Substring(0, inx).Trim().ToString();
DataTable dt = db.DTquer(xqry);
GridData.DataSource = dt;
GridData.Refresh();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
And here is the code in my DB.cs file that throws the error:
public DataTable DTquer(string thequer)
{
DataTable dt = new DataTable();
MakeCon();
// getConnection().Open();
MySqlCommand cmd = new MySqlCommand(thequer,getConnection());
try
{
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
getConnection().Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
return dt;
}
Thanks in Advance for all the help.
Do you need to do xqry = SelStr + finalqry.Substring(0, inx).Trim().ToString(); ?
(You have appended SelStr when it is shown in the MessageBox but not here)
I am building a simple Point of Sale program and working on a "search invoice" button that allows up to 3 search criteria (InvoiceID , ClientName, and ClientID). These are the names of 3 of the columns in the table named "Invoicing".
InvoiceID is the key column of type Int32, ClientName is of type String, ClientID is of type Int32. ClientName and ClientID searches work perfect.
MY PROBLEM: If I include InvoiceID in the select query, I get the following error. And I have spent a few days trying to figure it out.
ERROR: Database Error: Datatype mismatch in criteria expression.
Can you more experienced programmers help me out? thank you!
String connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data" + #" Source=TESTDB.accdb";
String tableName = "Invoicing";
String query = String.Format("select * from [{0}] where", tableName);
//ADD IN SEARCH CRITERIA
int filled = 0;
if (invoiceBox.Text != "") { query += " InvoiceID='" + invoiceBox.Text+"'"; filled += 1; }
/*if (DateCheckBox.Checked == true)
{
if (filled>=1) { query += " and DateNTime='" + monthCalendar1.SelectionStart.ToString() + "'"; filled += 1; }
else { query += " DateNTime='" + monthCalendar1.SelectionStart.ToString()+ "'"; filled += 1; }
}
* */
if (ClientNameBox.Text != "") //Doesnot work
{
if (filled >= 1) { query += " and Client='" + ClientNameBox.Text + "'"; filled += 1; }
else { query += " Client='" + ClientNameBox.Text + "'"; filled += 1; }
}
if (ClientIDBox.Text != "") //THIS search criteria works!!!!
{
if (filled >= 1) { query += " and ClientID='" + ClientIDBox.Text + "'"; filled += 1; }
else { query += " ClientID='" + ClientIDBox.Text + "'"; filled += 1; }
}
//CHECK IF SEARCH CRITERIA ARE PRESENT
if (filled < 1) { MessageBox.Show("At least One Search criteria above is required"); return; }
DataSet dsInvoicing = new DataSet();
OleDbConnection conn = new OleDbConnection(connectionString);
try
{
//Open Database Connection
conn.Open();
OleDbDataAdapter daInvoicing = new OleDbDataAdapter(query, conn);
//Fill the DataSet
daInvoicing.Fill(dsInvoicing, tableName);
//MessageBox.Show("dsInventory has "+dsInventory.Tables[0].Rows.Count+" search results");
conn.Close();
this.dataGridView1.DataSource = dsInvoicing.Tables[0];
}
catch (OleDbException exp){ MessageBox.Show("Database Error: " + exp.Message.ToString());}
Need more information? I will post up more if I haven't provided enough.
DATABASE INFORMATION or other.
Thank you very much to all programmers.
Looks like the data type of InvoiceID in your database is some numeric kind. While in query you are treating it as string. Try not to wrap InvoiceID value in single quotes.
I have a problem with the collectionpager and repeater. When I load the page, collectionpager is working fine.. But when I click the search button and bind new data, clicking the page 2 link, it is firing the page_load event handler and bring all the data back again... Notice: All controls are in an UpdatePanel.
protected void Page_Load(object sender, EventArgs e){
if (!IsPostBack)
{
kayit_getir("SELECT Tbl_Icerikler.ID,Tbl_Icerikler.url,Tbl_Icerikler.durum,Tbl_Icerikler.baslik,Tbl_Icerikler.gunc_tarihi,Tbl_Icerikler.kayit_tarihi,Tbl_Icerikler.sira,Tbl_Kategoriler.kategori_adi FROM Tbl_Icerikler,Tbl_Kategoriler where Tbl_Kategoriler.ID=Tbl_Icerikler.kategori_id ORDER BY Tbl_Icerikler.ID DESC,Tbl_Icerikler.sira ASC");
}}
public void kayit_getir(string SQL){
SqlConnection baglanti = new SqlConnection(f.baglan());
baglanti.Open();
SqlCommand komut = new SqlCommand(SQL, baglanti);
SqlDataAdapter da = new SqlDataAdapter(komut);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
CollectionPager1.DataSource = dt.DefaultView;
CollectionPager1.BindToControl = Liste;
Liste.DataSource = CollectionPager1.DataSourcePaged;
}
else
{
kayit_yok.Text = "<br /><span class='message information'>Kayıt bulunamadı.</span>";
}
da.Dispose();
baglanti.Close();
CollectionPager1.DataBind();
Liste.DataBind();}
protected void search_Click(object sender, EventArgs e){
string adi = f.temizle(baslik.Text);
string durum = Durum.SelectedValue;
string kayit_bas_t = kayit_bas_tarih.Text;
string kayit_bit_t = kayit_bit_tarih.Text;
string kategori = kategori_adi.SelectedValue;
string SQL = "SELECT Tbl_Icerikler.ID,Tbl_Icerikler.url,Tbl_Icerikler.durum,Tbl_Icerikler.baslik,Tbl_Icerikler.gunc_tarihi,Tbl_Icerikler.kayit_tarihi,Tbl_Icerikler.sira,Tbl_Kategoriler.kategori_adi FROM Tbl_Icerikler,Tbl_Kategoriler where Tbl_Kategoriler.ID=Tbl_Icerikler.kategori_id and";
if (adi != "")
{
SQL = SQL + " Tbl_Icerikler.baslik LIKE '%" + adi + "%' and";
}
if (kategori != "")
{
SQL = SQL + " Tbl_Icerikler.kategori_id=" + kategori + " and";
}
if (durum != "")
{
SQL = SQL + " Tbl_Icerikler.durum='" + durum + "' and";
}
if (kayit_bas_t != "")
{
SQL = SQL + " (Tbl_Icerikler.kayit_tarihi>'" + kayit_bas_t + "') and";
}
if (kayit_bit_t != "")
{
SQL = SQL + " (Tbl_Icerikler.kayit_tarihi<'" + kayit_bit_t + "') and";
}
SQL = SQL.Remove(SQL.Length - 3, 3);
SQL = SQL + " ORDER BY sira ASC,ID DESC";
try
{
kayit_getir(SQL);
}
catch { }
Recursive(0, 0);}
the code is very bad and you should completely review all of it.
the issue is every time the page load is executed it initializes again you query to the default one (the one with not filter) you should find a way to store somewhere the last query has been execute when you order/filtering your data.
Anyway the are lot of example on the web showing what you are trying to achieve
the below is just one of them
http://www.codeproject.com/KB/webforms/ExtendedRepeater.aspx
try this EnableViewState="false"
You have to bind the CollectionPager again on your search.