Why do I get this exception in my code? I restarted the server, changed ports, etc, but nothing is working.
What's wrong?
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection("server=localhost;user=armin;password=root;");
con.Open();
SqlCommand result = new SqlCommand(
"SELECT userid FROM KDDData.dbo.userprofile order by userid", con);
SqlDataReader reader = result.ExecuteReader();
dt.Load(reader);
List<string> userids = new List<string>(dt.Rows.Count);
foreach (DataRow item in dt.Rows)
{
userids.Add(item.ItemArray[0].ToString().Trim());
}
con.Close();
con = new SqlConnection("server=localhost;user=armin;password=root;");
con.Open();
foreach (string user in userids)
{
DataTable temp = new DataTable();
SqlCommand result1 = new SqlCommand(
"select itemid from KDDTrain.dbo.train where userid=" + user, con);
SqlDataReader reader1 = result1.ExecuteReader();
if (!reader1.HasRows)
{
continue;
}
temp.Load(reader1);
}
The first query works fine, but the second doesn't. As you can see I even use some other SqlConnection but it still doesn't work.
Note:The database i'm working with has atleast 100 milion records,thought may be this would be a problem.
Something doesn't look right in your connection string
I always seen "server=localhost; user=armin;password=root" in connections strings for MySql not for SqlServer where instead I will use "Data Source=(LOCAL);Integrated Security=SSPI" or the INSTANCE name of SqlServer. Are you sure that the first query works?.
However I think you should use the appropriate using statement
DataTable dt = new DataTable();
using(SqlConnection con = new SqlConnection("server=localhost;user=armin;password=root;"))
{
using(SqlCommand result = new SqlCommand(
"SELECT userid FROM KDDData.dbo.userprofile order by userid", con))
{
con.Open();
using(SqlDataReader reader = result.ExecuteReader())
{
dt.Load(reader);
List<string> userids = new List<string>(dt.Rows.Count);
foreach (DataRow item in dt.Rows)
{
userids.Add(item.ItemArray[0].ToString().Trim());
}
}
DataTable temp = new DataTable();
foreach (string user in userids)
{
using(SqlCommand result1 = new SqlCommand(
"select itemid from KDDTrain.dbo.train where userid=" + user, con))
{
using(SqlDataReader reader1 = result1.ExecuteReader())
{
if (!reader1.HasRows) continue;
temp.Load(reader1);
}
}
}
}
Please insert this line
result1.CommandTimeout = 0;
befor this line in the second query
SqlDataReader reader1 = result1.ExecuteReader();
Dispose your reader after:
foreach (DataRow item in dt.Rows)
{
userids.Add(item.ItemArray[0].ToString().Trim());
}
...and also close the connection after temp.Load(reader1). Also close the reader1.
Instead of all this... the clean way is to use USING for initializng the readers and connection. :)
Related
I have 2 datagridviews now i want to select a column named "Name" in the first datagridview and us it as the WHERE in my query to Select values from a table and put it in the other datagridview.
SqlCommand cmd = new SqlCommand();
cmd = ss.CreateCommand();
foreach (DataGridViewRow row in dgvAtt.Rows)
{
ss.Open();
cmd.CommandType = CommandType.Text;
string Query = "SELECT Signature FROM TBL_Student WHERE Name = '" +
row.Cells[4].Value.ToString() + "' ";
cmd.CommandText = Query;
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter dp = new SqlDataAdapter(cmd);
dp.Fill(dt);
dgvSign.DataSource = dt;
ss.Close();
}
but it gives me error when there is null and it is only selecting the first row in the first datagridview.
You create in each foreach-loop a new DataTable and therefore it will always just have one Value. So you have to create it before the foreach-loop.
And make sure you check the Values you want to use before using them.
With this easy if-condition, there won't be any problems.
Edit1:
This code snippet is working just fine.
Just change the ConnectionString and you are done.
DataTable dt = new DataTable();
string error;
using (SqlConnection con = new SqlConnection(#"Data Source=SERVER;Initial Catalog=DATEBASE; User ID=USERNAME; Password=PASSWORD"))
{
SqlCommand cmd = new SqlCommand();
foreach (DataGridViewRow row in dgvAtt.Rows)
{
string Query = "SELECT Signature FROM TBL_Student WHERE Name = '";
if (row.Cells.Count >= 4 && row.Cells[4].Value != null)
{
Query += row.Cells[4].Value.ToString();
}
Query += "'";
try
{
cmd = new SqlCommand(Query, con);
if (con.State == ConnectionState.Closed)
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
}
catch (Exception ex)
{
error = ex.Message;
}
}
}
dgvSign.DataSource = dt;
I want to get Data table values and save them in a single string, where dt.rows.Count is more that 0.
I want get menu_name, menu_Quantity and store them into a single string where email=ariffnaj#gmail.com.
If this is possible, can you show how to do it, this code only save into string at first column only
SqlConnection conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["connectionString"].ConnectionString);
string cartsql = "SELECT menu_name,menu_price,menu_quantity FROM cart where email=#email";
SqlCommand cmd1 = new SqlCommand(cartsql, conn);
cmd1.Parameters.AddWithValue("#email", Session["email"].ToString());
SqlDataAdapter sda = new SqlDataAdapter(cmd1);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
foreach (DataRow dtRow in dt.Rows)
{
string menuname = dtRow["menu_name"].ToString();
string menuprice = dtRow["menu_price"].ToString();
string menuquantity = dtRow["menu_quantity"].ToString();
}
}
You can try coalesce function:
DECLARE #str nvarchar(MAX)
SELECT #str = (COALESCE(#str + ';', '') + CONCAT('Menu:', menu_name, ', Quantity:', menu_quantity))
FROM cart WHERE email=#email
SELECT #str as output
And then use:String str = cmd1.ExecuteScalar().ToString();
My solution uses a SqlDataReader instead of SqlDataAdapter and DataTable. This is easier, if you only want to retrieve some values. To build the string I use a StringBuilder, as it manages the resources better than string concatenation would.
public string GetCartStringForEMail(string email)
{
const string sql = "SELECT menu_name, menu_quantity FROM cart WHERE email=#email";
string connectionString =
ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
using (var conn = new SqlConnection(connectionString))
using (var cmd = new SqlCommand(sql, conn)) {
var sb = new StringBuilder();
cmd.Parameters.AddWithValue("#email", email);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read()) {
sb.Append(reader.GetString(0))
.Append(", ")
.AppendLine(reader.GetInt32(1).ToString());
}
return sb.ToString();
}
}
Note that the using-statements automatically close the connection and release the resources.
I have this code:
listView10.Items.Clear();
MySqlConnection con = new MySqlConnection("Server=166.62.27.186;Database=xxxx;Uid=xxxx;Pwd=xxxx;");
MySqlCommand cmd = new MySqlCommand("select * from appoint order by times asc", con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
con.Open();
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
ListViewItem Item = new ListViewItem(dr["Customer"].ToString());
Item.SubItems.Add(dr["Kind"].ToString());
Item.SubItems.Add(dr["connum"].ToString() + "/" + dr["telnum"].ToString());
Item.SubItems.Add(dr["times"].ToString());
Item.SubItems.Add(dr["address"].ToString());
Item.SubItems.Add(dr["type"].ToString());
Item.SubItems.Add(dr["notes"].ToString());
listView10.Items.Add(Item);
}
con.Close()
it should load the value in the table but it doesn't.
When I connected the database to the Mysql Workbench it seems the connection is working. in my winform application it can insert into the database yet it still doesnt load. i as i observed I noticed that after executing :
da.Fill(dt);
It just stops there and doesn't execute the foreach statement. What seems to be the problem i don't understand.
I will provide more information if needed, im kinda in a rush tomorrow is our defense in our thesis. thanks in advance
pics when debugging
You can use DataTable.Load() method with MySqlDataReader.ExecuteReader() method as alternative to MySqlDataAdapter to retrieve data like this example:
using (MySqlConnection con = new MySqlConnection("Server=166.62.27.186;Database=xxxx;Uid=xxxx;Pwd=xxxx;"))
{
con.Open();
using (MySqlCommand cmd = new MySqlCommand("select * from appoint order by times asc", con))
{
MySqlDataReader rdr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rdr);
foreach (DataRow dr in dt.Rows)
{
ListViewItem Item = new ListViewItem(dr["Customer"].ToString());
Item.SubItems.Add(dr["Kind"].ToString());
Item.SubItems.Add(dr["connum"].ToString() + "/" + dr["telnum"].ToString());
Item.SubItems.Add(dr["times"].ToString());
Item.SubItems.Add(dr["address"].ToString());
Item.SubItems.Add(dr["type"].ToString());
Item.SubItems.Add(dr["notes"].ToString());
listView10.Items.Add(Item);
}
}
con.Close();
}
I'm trying to retrieve the names of the table from the local database I'm using.
This the code I've tried but it never goes through the foreach loop:
public void GetColumnNames()
{
SqlConnection con;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
con = new SqlConnection(Properties.Settings.Default.AlhusainSoundDBConnectionString);
List<string> colns = new List<string>();
try
{
con.Open();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
foreach (DataTable dt in ds.Tables)
{
colns.Add(dt.TableName);
Console.WriteLine(dt.TableName);
}
}
So could anyone please suggest me how to do that correctly
Regards
To get table names you need to use INFORMATION_SCHEMA
USE <your_database_name>
GO
SELECT * FROM INFORMATION_SCHEMA.TABLES
You haven't done anything except open a connection to the database. Your dataset has not been populated with any data. My approach would be to use a SqlCommand object to execute the following SQL Statement and populate a SqlDataReader
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
So, the C# code might look something like this:
string sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES";
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.AlhusainSoundDBConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, con))
{
con.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
// do something with each table
string tableName= dr["TABLE_NAME"].ToString();
// OR
// string tableName = dr[0].ToString();
// OR
// string tableName = dr.GetString(0);
}
}
}
I have the below code, which works, but is only reading the top row of the DB and then terminating. The array should hold 3 pieces of data, but it only holds one.
I think this is because it is not looping.
How do you say for the code to carry on running until it has no more data to read?
SqlConnection conn1 = new SqlConnection(ssConnectionString);
conn1.Open();
SqlCommand command1 = conn1.CreateCommand();
command1.CommandText = "SELECT FeedURL FROM [dbo].[Feeds]";
rssFeeds.Add(command1.ExecuteScalar());
conn1.Close();
By default ExecuteScalar() will only ever return one value. You would need to create a DataReader, and then loop through the results using command1.ExecuteReader()
conn1.Open();
string query = "select feedurl from [dbo].[feeds]";
DataSet DS = new DataSet();
SqlDataAdapter adapt = new SqlDataAdapter(query,conn1);
adapt.Fill(DS);
if (DS != null)
{
if (DS.Tables[0].rows.Count > 0 )
{
foreach(DataRow DR in DS.Tables[0].Rows)
{
string temp = DR['columnname'];
}
}
{
You can just use ExecuteReader for your problem. In this example that I took from MSDN is consuming the connection with using statement because SqlConnection class has some unmanaged resources. If you have more questions about using and Finalizers also check here.
How to use ExecuteReader, you can check here:
static void HasRows(SqlConnection connection)
{
using (connection)
{
SqlCommand command = new SqlCommand(
"SELECT CategoryID, CategoryName FROM Categories;",
connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
}
}
Try this:
//method to make this code reusable
//the returned data set is accessible even if the underlying connection is closed
//NB: that means data's held in memory; so beware of your resource usage
public DataSet ExecuteSQLToDataSet(string ssConnectionString, string query, string name)
{
DataSet ds = new DataSet("Tables");
using (SqlConnection conn1 = new SqlConnection(ssConnectionString))
{
conn1.Open();
SqlDataAdapter sda = new SqlDataAdapter(query, objConn);
sda.FillSchema(ds, SchemaType.Source, name);
sda.Fill(ds, name);
} //using statement will close and dispose the connection for you
return ds;
}
//example usage
DataSet ds = ExecuteSQLToDataSet(ssConnectionString, "SELECT FeedURL FROM [dbo].[Feeds]", "Feeds"); //nb: name doesn't have to match table name; you can call it what you like; naming is useful if you wanted to add other result sets to the same data set
//DataTable tblFeeds = ds.Tables["Feeds"]; //if you want to access the above query by name
foreach (DataTable tbl in ds.Tables)
{
foreach (DataRow dr in tbl.Rows) //tblFeeds.Rows if you did that instead of looping through all tables
{
//Console.WriteLine(dr["FeedURL"].ToString()); //you can specify a named column
Console.WriteLine(dr[0].ToString()); //or just use the index
}
}
Console.WriteLine("Done");
Console.ReadLine();
More Detail: http://support.microsoft.com/kb/314145