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)
Related
need some help with a simple code
This is for Visual Studio c# Win Forms
dgvScad.DataSource =
dataProvider.getAttestatiByScad(DateTime.Today.AddDays(dayScad),
DateTime.Today);
dgvProve.DataSource =
dataProvider.getAziendaliByScad(DateTime.Today.AddDays(dayScad),
DateTime.Today);
a
public DataTable getAttestatiByScad(DateTime scadenza1, DateTime scadenza2)
{
string sql = "SELECT CONCAT(Dipendenti.cognome, ' ', Dipendenti.nome) AS Nome, Attestati.nome AS Attestato, AssAttestati.scadenza AS Scadenza " +
" FROM Attestati INNER JOIN(AssAttestati INNER JOIN Dipendenti" +
" ON AssAttestati.matricola=Dipendenti.matricola) " +
" ON Attestati.ID=AssAttestati.attestato " +
" WHERE AssAttestati.scadenza<=#scadenza1 AND AssAttestati.scadenza>=#scadenza2;";
DataTable dt = db.EseguiQueryWithParams
(
sql,
new SqlParameter("#scadenza1", scadenza1),
new SqlParameter("#scadenza2", scadenza2)
);
return dt;
}
public DataTable getAziendaliByScad(DateTime scadenza1, DateTime scadenza2)
{
string sql = "SELECT Aziendali.nome, Aziendali.scadenza FROM Aziendali WHERE Aziendali.scadenza<=#scadenza1 AND Aziendali.scadenza>=#scadenza2";
DataTable dt = db.EseguiQueryWithParams
(
sql,
new SqlParameter("#scadenza1", scadenza1),
new SqlParameter("#scadenza2", scadenza2)
);
return dt;
}
public DataTable EseguiQueryWithParams(string sql, params SqlParameter[] parameters)
{
apriConnessione();
string nometab = "dump";
cmd.CommandText = sql;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddRange(parameters);
try
{
adp = new SqlDataAdapter(cmd);
if (dset.Tables[nometab] != null)
dset.Tables[nometab].Clear();
adp.Fill(dset, nometab);
DataTable d = dset.Tables[nometab];
//d.Columns;
return d;
}
catch (Exception e)
{
throw e;
//throw new System.Exception("Errore nella lettura della tabella");
}
finally
{
adp.Dispose();
cmd.Dispose();
ChiudiConnessione();
}
}
I excpect the output to be different results, but all I see its the same for one DataGridView and the other DataGridView.
Hope you understand what I wronte I'm not so good in English.
It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details.?
I have a program where i have to display
The Event Description (OpisDogodka)
Location (Lokacija)
Time (ura)
My table valued function:
[dbo].[DobiDogodek](
#Ime nvarchar(100), #Datum date)
RETURNS TABLE AS RETURN (SELECT OpisDogodka AS 'Opisdogodka',Lokacija, Ura FROM Dogodek WHERE Ime=#Ime AND Datum=#Datum)
My method to connect to the server:
public string Dobi_dogodek(string ime,string datum)
{
string a="";
cmd = new SqlCommand("SELECT * FROM dbo.DobiDogodek(#Ime,#Datum)",povezava); //povezava = connectio and it succeeds to connect to the server.
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Ime", ime);
cmd.Parameters.AddWithValue("#Datum", datum); //how to pass date only?
try
{
SqlDataReader Reader = cmd.ExecuteReader();
while(Reader.Read())
{
a = Reader.GetString(0)+" "+Reader.GetString(1)+" "+Reader.GetString(3).ToString(); // get what?
}
Uspeh = true;
}
catch (Exception e)
{
ex = e;
}
finally
{
povezava.Close();
}
return a;
}
I tried also using Datatable and datarow. I am also unsure how to work with Date. I know how to work with DateTime, but I need Date and Time separate. What I am doing wrong?
4.6.2017 (11.40 am CET)Update:
It seems I get the desired result
public List<string> Dobi_dogodek(string ime,string datum)
{
s = new List<string>();
cmd = new SqlCommand("SELECT * FROM dbo.DobiDogodek(#Ime,#Datum)",povezava);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Ime", ime);
cmd.Parameters.AddWithValue("#Datum", Convert.ToDateTime(datum));
dt = new DataTable();
da = new SqlDataAdapter(cmd);
da.Fill(dt);
try
{
foreach (DataRow dr in dt.Rows)
{
s.Add(dr["Opis dogodka"].ToString() + "\\" + dr["Lokacija"].ToString() + "\\" + dr["Ura"].ToString());
}
Uspeh = true;
}
catch (Exception e)
{
ex = e;
}
finally
{
povezava.Close();
}
return s;
}
Now I just need to split the strings according to my requirements, but is the a better (not necessarily an easy) way?
Try this:
cmd.Parameters.AddWithValue("#Datum", Convert.ToDateTime(datum));
See also https://msdn.microsoft.com/en-us/library/cc716729(v=vs.110).aspx .
what is happening when you run it? are you getting an error message? is it getting it as an int? did you see what the sql server is getting from application by using sql profiler?
I will double check but I think your problem is you are not putting quotes around your variables in our statement so when it runs it is evaluating them as ints. try "SELECT * FROM dbo.DobiDogodek('#Ime','#Datum')". It been a long time since I havnt used something like EF...
I have an difficult situation :
this is my form :
the first button '...' is a btnAllegato. Code :
private void btnAllegato_Click(object sender, EventArgs e)
{
try
{
using (OpenFileDialog openFileDialog1 = new OpenFileDialog())
{
string path = string.Empty;
openFileDialog1.Title = "Seleziona richiestaIT (PDF)..";
openFileDialog1.Filter = ("PDF (.pdf)|*.pdf");
openFileDialog1.FilterIndex = 1;
openFileDialog1.FileName = "";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
//salva l'intero path
path = openFileDialog1.FileName;
//nome file + estensione
string temp = openFileDialog1.SafeFileName;
//elimina l'estensione del file con IgnoreCase -> case Unsensitive
temp = Regex.Replace(temp, ".pdf", " ", RegexOptions.IgnoreCase);
//datatime + replace
string timenow = System.DateTime.Now.ToString();
//replace data da gg//mm/aaaa ss:mm:hh -----> ad gg-mm-aaaa_ss-mm-hh
timenow = timenow.Replace(":", "-").Replace("/", "-");//.Replace(" ", " ");
_url = #"\\192.168.5.7\dati\SGI\GESTIONE IT\RichiesteIT\" + temp + timenow + ".pdf";
System.IO.File.Copy(path, _url);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
after i have a button Inserisci >> (btnInserisci)
with this button i Create a DB Query to insert data...
private void btnInserisci_Click(object sender, EventArgs e)
{
try
{
if ((_IDRichiedente != -1) && (_data != string.Empty) && (_url != string.Empty))
{
MessageBox.Show(_url);
QueryAssist qa = new QueryAssist();
string query = "INSERT INTO RICHIESTA_IT(ID_Risorsa, descrizione_richiesta, modulo_pdf, data_richiesta) VALUES('" + _IDRichiedente + "', '" + txtBreveDescrizione.Text + "', '" + _url + "', '" + _data + "');";
MessageBox.Show(query);
qa.runQuery(query);
else
{
MessageBox.Show("Selezionare il richiedente,data o allegato!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
where
private int _IDRichiedente = -1;
private string _data = String.Empty;
private string _url = string.Empty;
is a fields of class.
QueryAssist is my class that connect, run query and disconnect to Access DB.
code :
class QueryAssist
{
System.Data.OleDb.OleDbConnection _OleDBconnection;
public QueryAssist()
{
this._OleDBconnection = null;
}
private bool connectionDB()
{
string connection = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=\"\\\\192.168.5.7\\dati\\Scambio\\Sviluppo\\Impostazioni temporanea db Censimento\\CensimentoIT.accdb\"";
try
{
_OleDBconnection = new System.Data.OleDb.OleDbConnection(connection);
_OleDBconnection.Open();
return true;
}
catch(Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
return false;
}
}
private void disconnectDB()
{
try
{
_OleDBconnection.Close();
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
}
public System.Data.DataTable runQuery(string query)
{
try
{
if (connectionDB())
{
System.Data.DataTable dataTable = new System.Data.DataTable();
System.Data.OleDb.OleDbCommand sqlQuery = new System.Data.OleDb.OleDbCommand(query, _OleDBconnection);
System.Data.OleDb.OleDbDataAdapter adapter = new OleDbDataAdapter(sqlQuery);
adapter.Fill(dataTable);
disconnectDB();
return dataTable;
}
}
catch(Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
return null;
}
public int countRowsQueryResult(string query)
{
try
{
if (connectionDB())
{
System.Data.DataTable dataTable = new System.Data.DataTable();
System.Data.OleDb.OleDbCommand sqlQuery = new System.Data.OleDb.OleDbCommand(query, _OleDBconnection);
System.Data.OleDb.OleDbDataAdapter adapter = new OleDbDataAdapter(sqlQuery);
adapter.Fill(dataTable);
disconnectDB();
return dataTable.Rows.Count;
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
return -1;
}
}
At firt time ... The application work good. I selected a file and other data and I click on button 'Inserisci>>' and all working good.
Next step when i want to insert other data ... when i click on '...' button for attachment a file i have the loop OpenFileDialog
To close, i must kill the process.
I have [STAThread] set on main of the program.
Connect to NAS isn't a problem ... I have try in local .. and i have the same problem..
If i click on btn '...' to OpenFileDialg then not click on button 'Inserisci>>'
OpenFileDialog work good for all time ...
But if i click on button 'Inserisci>>' on the next click on button '...' to OpenFileDialog application loop..
Sorry for bad english ..I'm here for clarification
The use of the runQuery method with an INSERT statement could be the cause of your problems. To insert a record you should use an OleDbCommand with the ExecuteNonQuery. A Fill method is used to fill a DataTable.
The fact that the record is inserted anyway happens because the underlying command used to fill the DataTable (ExecuteReader) ignores its sql command text and executes what you have passed. However after that the Fill method expects to fill a DataTable and not having a select statement could be potentially the cause of your problems.
I would use a different method when you need to Update/Delete or Insert new data
public int runNonQuery(string query)
{
try
{
if (connectionDB())
{
OleDbCommand sqlQuery = new OleDbCommand(query, _OleDBconnection);
int rows = sqlQuery.ExecuteNonQuery();
disconnectDB();
return rows;
}
}
catch(Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
return -1;
}
}
There are other problems in your code and are all connected to the way in which you concatenate together the string to form an sql statement. This is know as the worst practice possible with database code. If you take a bit of your time to investigate how to write a parameterized query you will avoid a lot of future problems.
I'm trying to write data back into a file on Unidata, after the contents have been adjusted in a datagridview.
I've tried various option based around the code below, but with no luck.
Within the foreach section I want to update my file.
The file consists of 10 single value attributes.
I tried fl.write(),but get an error relating to writing to a null value...
try
{
DataTable modifiedTable = m_DS.Tables[0].GetChanges(DataRowState.Modified);
if (modifiedTable.Rows.Count > 0)
{
U2Connection con = GetConnection();
Console.WriteLine("Connected.................");
UniSession lUniSession = con.UniSession;
UniFile fl = lUniSession.CreateUniFile("myTableName");
UniDynArray udr3 = new UniDynArray(lUniSession);
foreach (DataRow item in modifiedTable.Rows)
{
}
con.Close();
}
}
Thank you for using UniObjects’s API of U2 Toolkit for .NET (formerly known as standalone UO.NET).
Yesterday (June 10th, 2014) , we have Released U2 Toolkit for .NET v2.1.0. Main features of U2 Toolkit for .NET v2.1.0 is
Native Visual Studio Integration
For other features, see this link
http://blog.rocketsoftware.com/2014/05/access-nosql-data-using-sql-syntax-u2-toolkit-net-v2-1-0-beta/
Can you please try the same code ( 10 single value attributes) using SELECT and UPDATE. For your information, SELECT and UPDATE behind the scene calls UniFile Read and Write. These Samples are part of the installation. Go to these directories.
C:\Program Files (x86)\Rocket Software\U2 Toolkit for .NET\U2 Database Provider\samples\C#\UniData\NativeAccess\Select_SQL_Syntax
C:\Program Files (x86)\Rocket Software\U2 Toolkit for .NET\U2 Database Provider\samples\C#\UniData\NativeAccess\Update_SQL_Syntax
SELECT
private static void Select()
{
try
{
Console.WriteLine(Environment.NewLine + "Start...");
ConnectionStringSettingsCollection settings = ConfigurationManager.ConnectionStrings;
ConnectionStringSettings cs = settings["u2_connection"];
U2Connection lConn = new U2Connection();
lConn.ConnectionString = cs.ConnectionString;
lConn.Open();
Console.WriteLine("Connected...");
U2Command cmd = lConn.CreateCommand();
//ID,FNAME,LNAME : Single Value
//SEMESTER: Multi Value
//COURSE_NBR,COURSE_GRD: MS
cmd.CommandText = string.Format("SELECT ID,FNAME,LNAME,SEMESTER,COURSE_NBR,COURSE_GRD FROM STUDENT WHERE ID > 0 ORDER BY ID");
U2DataAdapter da = new U2DataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
Console.WriteLine(Environment.NewLine);
ds.WriteXml(Console.Out);
lConn.Close();
Console.WriteLine(Environment.NewLine + "End...");
Console.WriteLine(SUCCESS_MSG);
}
catch (Exception e2)
{
string lErr = e2.Message;
if (e2.InnerException != null)
{
lErr += lErr + e2.InnerException.Message;
}
Console.WriteLine(Environment.NewLine + lErr);
Console.WriteLine(FAIL_MSG);
}
}
Update
private static void Update_Using_DataSet()
{
try
{
Console.WriteLine(Environment.NewLine + "Start...");
ConnectionStringSettingsCollection settings = ConfigurationManager.ConnectionStrings;
ConnectionStringSettings cs = settings["u2_connection"];
U2Connection lConn = new U2Connection();
lConn.ConnectionString = cs.ConnectionString;
lConn.Open();
Console.WriteLine("Connected...");
U2Command cmd = lConn.CreateCommand();
//ID,FNAME,LNAME : Single Value
//SEMESTER: Multi Value
//COURSE_NBR,COURSE_GRD: MS
cmd.CommandText = string.Format("SELECT ID,FNAME,LNAME,SEMESTER,COURSE_NBR,COURSE_GRD FROM STUDENT WHERE ID={0} ORDER BY ID",ID);
U2DataAdapter da = new U2DataAdapter(cmd);
U2CommandBuilder builder = new U2CommandBuilder(da);
da.UpdateCommand = builder.GetUpdateCommand();
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
DataRowCollection lDataRowCollection = dt.Rows;
int i = 1;
foreach (DataRow item in lDataRowCollection)
{
item["FNAME"] = item["FNAME"] + "3";// modify single value
item["SEMESTER"] = item["SEMESTER"] + "$";//modify multi-value
item["COURSE_GRD"] = item["COURSE_GRD"] + "$";
i++;
}
da.Update(ds);//use DataAdapter's Update() API
//print modified value
cmd.CommandText = string.Format("SELECT ID,FNAME,LNAME,SEMESTER,COURSE_NBR,COURSE_GRD FROM STUDENT WHERE ID={0} ORDER BY ID", ID); ;
//verify the change
U2DataAdapter da2 = new U2DataAdapter(cmd);
DataSet ds2 = new DataSet();
da2.Fill(ds2);
Console.WriteLine(Environment.NewLine);
ds2.WriteXml(Console.Out);
//close connection
lConn.Close();
Console.WriteLine(Environment.NewLine + "End...");
Console.WriteLine(SUCCESS_MSG);
}
catch (Exception e2)
{
Console.WriteLine(FAIL_MSG);
string lErr = e2.Message;
if (e2.InnerException != null)
{
lErr += lErr + e2.InnerException.Message;
}
Console.WriteLine(Environment.NewLine + lErr);
}
}
You will need to modify the UniDynArray (the record) for each row value in the table and then write the UniDynArray to the file and specific record id:
for (Int32 i=0; i < modifiedTable.Rows.Count; i++)
{
DataRow item = modifiedTable.Rows[i];
//Modify each attribute in the record from the rows in the table
udr3.Replace(i+1, (String)item[0]);
}
//Write the modified record to the file
fl.Write("MyRecordId", udr3);
The reason you got the null reference exception is because you didn't assign a value to fl.RecordId or fl.Record before calling fl.Write(). As you can see above, I prefer to use the overload of the Write method that takes record id and record data as parameters instead of setting the properties on the instance of UniFile.
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.