I'm using OleDbDataAdapter class to get data from an Access (.mdb) file.
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Environment.CurrentDirectory+"\\Data.mdb;Jet OLEDB:Database Password=pass");
OleDbCommand com = new OleDbCommand(query, con);
DataTable dt = new DataTable();
con.Open();
OleDbDataAdapter oda = new OleDbDataAdapter(com);
oda.Fill(dt);
oda.Dispose();
com.Parameters.Clear();
con.Close();
return dt;
The problem is that by debugging I found out, oda.Fill(dt) takes a very long time to execute. (around 10 seconds)
I have 50,000 records in the database and I only need to retrieve 1 row.
Please help. Thank you in advance.
If all you need is one row try using a data reader as shown below, of your you will need to adjust pieces like database name, field list etc.
Note I write output to the IDE Output window so have it open when trying this with your code/data.
public partial class Form1 : Form
{
private void button1_Click(object sender, EventArgs e)
{
int id = 0;
if (int.TryParse(textBox1.Text, out id))
{
OleDbConnectionStringBuilder Builder = new OleDbConnectionStringBuilder();
Builder.Provider = "Microsoft.Jet.OLEDB.4.0";
Builder.DataSource = Path.Combine(Application.StartupPath, "Database1.mdb");
using (OleDbConnection cn = new OleDbConnection(Builder.ConnectionString))
{
string selectStatement = "SELECT UserName, JoinMonth FROM Users WHERE Identifier = #Identifier";
using (OleDbCommand cmd = new OleDbCommand { CommandText = selectStatement, Connection = cn })
{
cmd.Parameters.Add(new OleDbParameter { ParameterName = "#Identifier", DbType = DbType.Int32, Value = id });
cn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
dr.Read();
Console.WriteLine("{0} - {1}", dr.GetString(0), dr.GetString(1));
}
else
{
Console.WriteLine("Not located");
}
}
}
}
}
}
Related
I want insert some data to localdatabace and insert is successfully done but don't show in my datagridview tile second insert do for debog it I Call Select All end of my insert and see the last insert don't show in it but whene i insert a next data , last data will be showing can every one help me pleas?
public void connect()
{
String conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\hana\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection sql = new SqlConnection(conString);
String sqll = "Insert into TblBank (txtTodayDate" +
",txtSahebanHesab" +
",txtShobe" +
",txtShomareMoshtari" +
",txtShoareHesab" +
",cmbNoeHesab" +
",txtSarresid" +
")";
try
{
sql.Open();
SqlDataAdapter sda = new SqlDataAdapter(sqll, sql);
SqlCommand sc = new SqlCommand(sqll,sql);
sc.Parameters.AddWithValue("todayDate", new PersianDateTime(dtpTodayDate.the_date).ToString("yyyy/MM/dd"));
sc.Parameters.AddWithValue("sahebanHesab", txtSahebHesabName.Text);
sc.Parameters.AddWithValue("shobe", txtshobe.Text);
sc.Parameters.AddWithValue("shomareMoshtari", txtShomareMoshtari.Text);
sc.Parameters.AddWithValue("shoareHesab", txtShomareHesab.Text);
sc.Parameters.AddWithValue("noeHesab", cmbNoeHesab.SelectedIndex);
sc.Parameters.AddWithValue("sarresid", txtSarResidMah.Text);
sc.ExecuteNonQuery();
sql.Close();
select();
}
catch (Exception ex)
{
}
}
and select is
private void select()
{
String conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\hana\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection cn = new SqlConnection(conString);
String sqlString = "SELECT * FROM TblBank Order BY Id desc ";
SqlConnection sql = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand(sqlString, cn);
try {
sql.Open();
SqlDataAdapter sa = new SqlDataAdapter(sqlString, sql);
using (SqlDataReader read = sa.SelectCommand.ExecuteReader())
{
if (read.Read())
{
DataTable dt = new DataTable();
dt.Load(read);
this.tblBankDataGridViewX.DataSource = dt;
}
}
sql.Close();
}
catch (Exception ex)
{
}
}
The DataReader.Read() method will iterate result set before DataTable.Load(). Because the DataReader is a forward-only stream, it has empty result set when DataTable.Load() executes and DataTable content is still empty while setting DataSource for DataGridView. Try DataReader.HasRows property to check result set availability:
using (SqlConnection cn = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(sqlString, cn))
{
try
{
cn.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
// check if the reader returns result set
if (read.HasRows)
{
DataTable dt = new DataTable();
dt.Load(read);
this.tblBankDataGridViewX.DataSource = dt;
}
}
}
catch (Exception ex)
{
// do something
}
}
}
i'm writing a code on c# (winform). the program is about cachier and the database is
ms access.
when i am entering the data to the database it seems like the data was enterd but when i'm opening the ms access the table is empty. althogh, if i right click on the 'preview data set' in the visual studio, i can see the data.
here is my code so far regard to the database:
private void buttonCloseCart_Click(object sender, EventArgs e)
{
for (int i = 0; i < baught_items.Count; i++)
{
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\אורון\documents\visual studio 2012\Projects\CachierPro\CachierPro\CachierProDB.accdb";
string temp_item = baught_items[i].ToString();
int temp_item_quantity = baught_items_quantity[i];
double temp_item_price = baught_items_price[i];
double temp_total_item_price = total_items_price[i];
connect.Open();
OleDbCommand cmd = new OleDbCommand("INSERT INTO Receipts (ItemName, Quantity, PricePerOne, Total) VALUES (#temp_item, #temp_item_quantity, #temp_item_price, #temp_total_item_price)", connect);
if (connect.State == ConnectionState.Open)
{
cmd.Parameters.Add ("#temp_item", OleDbType.Char, 20).Value = temp_item;
cmd.Parameters.Add("#temp_item_quantity", OleDbType.Integer, 20).Value = temp_item_quantity;
cmd.Parameters.Add("#temp_item_price", OleDbType.Double, 20).Value = temp_item_price;
cmd.Parameters.Add("#cart_sum", OleDbType.Double,20).Value = temp_total_item_price;
try
{
cmd.ExecuteNonQuery();
OleDbDataAdapter da = new OleDbDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
MessageBox.Show("Data Added To DataBase");
textBoxCurrentCartSumTXT.Clear();
textBoxPricePerOneTXT.Clear();
textBoxQuantityTXT.Clear();
textBoxSumForCurrentItemTXT.Clear();
connect.Close();
}
catch (Exception expe)
{
MessageBox.Show(expe.Source);
connect.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
}
To get any rows back from your database storage through a OleDbDataAdapter you need to set its SelectCommand with a command that contains a SELECT statement
da.SelectCommand = new OleDbCommand("SELECT * FROM Receipts", connect);
DataTable dt = new DataTable();
da.Fill(dt);
Actually you are using the same command used to INSERT data as it was the SelectCommand. Obviously it doesn't return records. You should have a duplicate record in your table.
I would change something to your code. If you have more than one record to add to your table (you have a loop there) then there is no sense in extracting data from your db at every loop. I would call the Fill of the table outside the loop. Also a bit performance gain could be obtained defining the OleDbCommand and its parameters just one time before entering the loop. Inside the loop just update the values of the parameters and call ExecuteNonQuery
private void buttonCloseCart_Click(object sender, EventArgs e)
{
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\אורון\documents\visual studio 2012\Projects\CachierPro\CachierPro\CachierProDB.accdb";
connect.Open();
OleDbCommand cmd = new OleDbCommand(#"INSERT INTO Receipts
(ItemName, Quantity, PricePerOne, Total)
VALUES (#temp_item, #temp_item_quantity,
#temp_item_price, #temp_total_item_price)", connect);
cmd.Parameters.Add ("#temp_item", OleDbType.Char, 20);
cmd.Parameters.Add("#temp_item_quantity", OleDbType.Integer, 20);
cmd.Parameters.Add("#temp_item_price", OleDbType.Double, 20);
cmd.Parameters.Add("#cart_sum", OleDbType.Double,20);
for (int i = 0; i < baught_items.Count; i++)
{
string temp_item = baught_items[i].ToString();
int temp_item_quantity = baught_items_quantity[i];
double temp_item_price = baught_items_price[i];
double temp_total_item_price = total_items_price[i];
if (connect.State == ConnectionState.Open)
{
cmd.Parameters["#temp_item"].Value = temp_item;
cmd.Parameters["#temp_item_quantity"].Value = temp_item_quantity;
cmd.Parameters["#temp_item_price"].Value = temp_item_price;
cmd.Parameters["#cart_sum"].Value = temp_total_item_price;
try
{
int addedCount = cmd.ExecuteNonQuery();
if(addedCount == 0)
{
... problems here, record not added for some reasons
}
}
catch (Exception expe)
{
MessageBox.Show(expe.Source);
connect.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
OleDbDataAdapter da = new OleDbDataAdapter();
da.SelectCommand = new OleDbCommand("SELECT * FROM Receipts", connect);
DataTable dt = new DataTable();
da.Fill(dt);
textBoxCurrentCartSumTXT.Clear();
textBoxPricePerOneTXT.Clear();
textBoxQuantityTXT.Clear();
textBoxSumForCurrentItemTXT.Clear();
connect.Close();
}
I have created a web page in Asp.net website. The following page load will run as it gets arguments from previous page. The page also has an option for editing the contents and updating in database. But when the button(save) is clicked it doesn't update the database.Kindly help in this. But when there is no connection in page load the update command works.
protected void Page_Load(object sender, EventArgs e)
{
String cust=Request.QueryString["custName"];
String env = Request.QueryString["env"];
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
SqlDataAdapter adapter = new SqlDataAdapter();
cnn.ConnectionString = connStr;
cnn.Open();
view();
if (env == "Production")
{
DataSet MyDataSet = new DataSet();
adapter = new SqlDataAdapter("Select * from Customer_Production where Customer_Name=#cust", cnn);
SqlCommandBuilder m_cbCommandBuilder = new SqlCommandBuilder(adapter);
cnn.Close();
//SqlCommand cmd = new SqlCommand("Select * from Customer_Production where Customer_Name=#cust", cnn);
adapter.SelectCommand.Parameters.AddWithValue("#cust", cust);
adapter.Fill(MyDataSet, "Servers");
foreach (DataRow myRow in MyDataSet.Tables[0].Rows)
{
custName.Value = myRow["Customer_name"].ToString();
custMaintain.Value= myRow["Customer_Maintenance"].ToString();
serviceAffect.Value=myRow["Systems/Services_Affected"].ToString();
email_Content.Value= myRow["Email_Content"].ToString();
email_Signature.Value= myRow["Email_Signature"].ToString();
email_From.Value=myRow["Email_From"].ToString();
email_To.Value=myRow["Email_To"].ToString();
email_Cc.Value=myRow["Email_Cc"].ToString();
email_Bcc.Value=myRow["Email_Bcc"].ToString();
}
}
else
{
DataSet MyDataSet = new DataSet();
adapter = new SqlDataAdapter("Select * from Customer_Non_Production where Customer_Name=#cust", cnn);
SqlCommandBuilder m_cbCommandBuilder = new SqlCommandBuilder(adapter);
cnn.Close();
//SqlCommand cmd = new SqlCommand("Select * from Customer_Production where Customer_Name=#cust", cnn);
adapter.SelectCommand.Parameters.AddWithValue("#cust", cust);
adapter.Fill(MyDataSet, "Servers");
foreach (DataRow myRow in MyDataSet.Tables[0].Rows)
{
custName.Value = myRow["Customer_name"].ToString();
custMaintain.Value = myRow["Customer_Maintenance"].ToString();
serviceAffect.Value = myRow["Systems/Services_Affected"].ToString();
email_Content.Value = myRow["Email_Content"].ToString();
email_Signature.Value = myRow["Email_Signature"].ToString();
email_From.Value = myRow["Email_From"].ToString();
email_To.Value = myRow["Email_To"].ToString();
email_Cc.Value = myRow["Email_Cc"].ToString();
email_Bcc.Value = myRow["Email_Bcc"].ToString();
}
}
The following is the button click for Save Button(for update command)
protected void save_click(object sender, EventArgs e)
{
//Button Click Save
/* String id = "A";
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
SqlDataAdapter adapter = new SqlDataAdapter();
cnn.ConnectionString = connStr;
cnn.Open();
String sql = String.Format("Update Customer_Production set Email_Signature='{0}' where Customer_Name like '{1}'",TextBox1.Text,id);
SqlCommand cmd = new SqlCommand(sql, cnn);
cmd.ExecuteNonQuery();
*/
String cust = "A";
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
SqlDataAdapter adapter = new SqlDataAdapter();
cnn.ConnectionString = connStr;
cnn.Open();
if (env.Value == "Production")
{
//String sql = String.Format("Update Customer_Production set Customer_Maintenance='{0}',Environment='{1}',[Systems/Services_Affected]='{2}',Email_Content='{3}',Email_Signature='{4}',Email_To='{5}',Email_Cc='{6}',Email_Bcc='{7}',Email_From='{8}' where Customer_Name like '{9}' ", "custMaintain.Value","env.Value","serviceAffect.Value","email_Content.Value","email_To.Value","email_Cc.Value","email_Bcc.Value","email_From.Value", "cust");
String sql = String.Format("Update Customer_Production set Email_Signature='{0}' where Customer_Name like '{1}'", email_Signature.Value,cust);
SqlCommand cmd = new SqlCommand(sql, cnn);
cmd.ExecuteNonQuery();
}
else
{
}
}
I'm not sure why having a connection (or not) in the Page_Load would make a difference, but here's one thing that looks off to me:
String.Format(
"Update Customer_Production set Email_Signature='{0}' where Customer_Name like '{1}'",
email_Signature.Value,
cust);
(I broke it into several lines because the part I'm interested in is the last part of the format string.)
You've set cust to "A" earlier in that method. So the SQL that will result will look (at the end) like this:
... where Customer_Name like 'A'
Unless you have a customer name that is exactly equal to A, that's not going to return anything, and therefore no records will be updated. You're forgetting the '%' wildcard.
I agree with all those who have pointed out that your code is vulnerable to SQL injection (and you'll also have a problem with single quotes), but just to show you what it needs to look like, here it is with the wildcard:
Update Customer_Production set Email_Signature='{0}' where Customer_Name like '{1}%'
I am entering the source name userid and password through the textbox and want the database list should be listed on the combo box so that all the four options sourcename, userid, password and databasename can be selected by the user to perform the connectivity
The databases are to be retrieve from other system as per the user. User will enter the IP, userid and password and they should get the database list in the combo box so that they can select the required database and perform the connectivity
private void frmConfig_Load(object sender, EventArgs e)
{
try
{
string Conn = "server=servername;User Id=userid;" + "pwd=******;";
con = new SqlConnection(Conn);
con.Open();
da = new SqlDataAdapter("SELECT * FROM sys.database", con);
cbSrc.Items.Add(da);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I am trying to do this but it is not generating any data
sys.databases
SELECT name
FROM sys.databases;
Edit:
I recommend using IDataReader, returning a List and caching the results. You can simply bind your drop down to the results and retrieve the same list from cache when needed.
public List<string> GetDatabaseList()
{
List<string> list = new List<string>();
// Open connection to the database
string conString = "server=xeon;uid=sa;pwd=manager; database=northwind";
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
// Set up a command with the given query and associate
// this with the current connection.
using (SqlCommand cmd = new SqlCommand("SELECT name from sys.databases", con))
{
using (IDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
list.Add(dr[0].ToString());
}
}
}
}
return list;
}
First add following assemblies:
Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Management.Sdk.Sfc.dll
Microsoft.SqlServer.Smo.dll
from
C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\
and then use below code:
var server = new Microsoft.SqlServer.Management.Smo.Server("Server name");
foreach (Database db in server.Databases) {
cboDBs.Items.Add(db.Name);
}
you can use on of the following queries:
EXEC sp_databases
SELECT * FROM sys.databases
Serge
Simply using GetSchema method:
using (SqlConnection connection = GetConnection())
{
connection.Open();
DataTable dtDatabases = connection.GetSchema("databases");
//Get database name using dtDatabases["database_name"]
}
using (var connection = new System.Data.SqlClient.SqlConnection("ConnectionString"))
{
connection.Open();
var command = new System.Data.SqlClient.SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "SELECT name FROM master.sys.databases";
var adapter = new System.Data.SqlClient.SqlDataAdapter(command);
var dataset = new DataSet();
adapter.Fill(dataset);
DataTable dtDatabases = dataset.Tables[0];
}
How to get list of all database from sql server in a combobox using c# asp.net windows application
try
{
string Conn = "server=.;User Id=sa;" + "pwd=passs;";
SqlConnection con = new SqlConnection(Conn);
con.Open();
SqlCommand cmd = new SqlCommand();
// da = new SqlDataAdapter("SELECT * FROM sys.database", con);
cmd = new SqlCommand("SELECT name FROM sys.databases", con);
// comboBox1.Items.Add(cmd);
SqlDataReader dr;
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
//comboBox2.Items.Add(dr[0]);
comboBox1.Items.Add(dr[0]);
}
}
// .Items.Add(da);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Try this:
SqlConnection con = new SqlConnection(YourConnectionString);
SqlCommand cmd = new SqlCommand("SELECT name from sys.databases", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
cbSrc.Items.Add(dr[0].ToString());
}
con.Close();
or this:
DataSet ds = new DataSet();
SqlDataAdapter sqlda = new SqlDataAdapter("SELECT name from sys.databases", YourConnectionString);
sqlda.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
cbSrc.Items.Add(ds.Tables[0].Rows[i][0].ToString());
}
public static List<string> GetAllDatabaseNamesByServerName(string ServerName, [Optional] string UserID, [Optional] string Password)
{
List<string> lstDatabaseNames = null;
try
{
lstDatabaseNames = new List<string>();
//string servername = System.Environment.MachineName;
string newConnString = string.Format("Data Source={0};", ServerName);
if (UserID == null)
{
newConnString += "Integrated Security = True;";
}
else
{
newConnString += string.Format("User Id ={0}; Password={1};", UserID, Password);
}
SqlConnection con = new SqlConnection(newConnString);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT name FROM master.sys.databases", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow row in dt.Rows)
{
lstDatabaseNames.Add(row[0].ToString());
}
con.Close();
return lstDatabaseNames;
}
finally
{
}
}
I have a username db table that I'm trying to connect with to compare the username/pass.
Here is my code, it's not working, what am I doing wrong?
DataTable dt = null;
protected void btn_Click_Login(object sender, EventArgs e)
{
string query = string.Format("SELECT * FROM Users WHERE Username='{0}' AND Password='{1}'", txtUsername.Text, txtPassword.Text);
using (SqlConnection c = new SqlConnection(ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString))
{
c.Open();
using (SqlDataAdapter a = new SqlDataAdapter(query, c))
{
DataTable t = new DataTable();
a.Fill(t);
}
}
if (dt.Rows.Count > 0)
{
Session["Username"] = txtUsername.Text;
Session["Password"] = txtPassword.Text;
Response.Redirect("main.aspx");
lblError.Text = "success";
}
else
{
lblError.Text = "Wrong Username/Password combination";
}
}
}
most probably you are using wrong datatable to check no of rows returned.
Check for t and dt instances of datatable.
Try creating a SqlCommand to hold your query.
SqlCommand cmd = new SqlCommand(query, c);
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
{
DataTable t = new DataTable();
a.Fill(t);
}
I'm not 100% sure that's your issue, but back in the days when i used to use ADO.NET (before L2SQL/EF, dark days indeed), i seem to remember an issue with DataTable's and SqlDataAdapter.
From what i remember - you can't fill a DataTable with a SqlDataAdapter based on a raw query string - you need to use SqlCommand. But i believe this can be accomplished with DataSet.
So either change to SqlCommand, or change to DataSet.
You fill t:
DataTable t = new DataTable();
a.Fill(t);
but read dt:
if (dt.Rows.Count > 0)
I decided to try the data reader and got it working:
protected void btn_Click_Login(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["RbConnectionString"].ConnectionString);
conn.Open();
string queryString = "SELECT * FROM [Users] WHERE Username=#username AND Password= #password";
SqlCommand command = new SqlCommand(queryString, conn);
command.Parameters.AddWithValue("#username", txtUsername.Text);
command.Parameters.AddWithValue("#password", txtPassword.Text);
SqlDataReader reader = null;
reader = command.ExecuteReader();
if (reader.Read())
{
Session["Username"] = txtUsername.Text;
Session["Password"] = txtPassword.Text;
Response.Redirect("main.aspx");
}
else
{
lblError.Visible = true;
lblError.Text = "Incorrect Username/Password Combination";
}
conn.Close();
}
What error you are getting is not clear. But i feel your connection is open and is never closed. Try
c.Close();