Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I still new to C# and just have 3 months plus of learning process. I would like to seeking advice on how to extract data value from my DataTable I have create for validation checking.
private void checker
{
string sqlSelect2 = "SELECT a.AccNo, a.CompanyName , a.CreditLimit, FROM Debtor a JOIN";
}
which i have named TableCehecker, i do not need to put it to gridview, just for checking purposes.
In the private void process how can I extract dataTable TableCehecker and the value?
Thank you,
Brian
You need to follow the Docs from MSDN:
SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "SELECT * FROM Customers";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.
DataTable dt = new DataTable();
dt.Load(reader);
sqlConnection1.Close();
You can then check whatever you want of data inside the DataTable either by querying or by looping through the rows and checking the column values.
Based on your comments, to extract values from single row:
DataRow drow = dt.Rows[0];
string value = drow.Field<string>("CompanyName");
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I search on the net to execute oracle stored function and get the value of it
and I found something similar to this but i don't really understand it so i am not able to find out what's the error with it... please if someone can explan
whats happening after opening the connection with the database ?
public void Get_Office_Desc()
{
string oradb = "Data Source=mysource;User Id=emp;Password=00;";
var v_Office_code = Current_Office_code.Text;
string CommandStr = "F_Get_Office_Desc(:pOfficeCode)";
using (OracleConnection conn = new OracleConnection(oradb))
using (OracleCommand cmd = new OracleCommand(CommandStr, conn))
{
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new OracleParameter("pOfficeCode", v_Office_code));
cmd.Parameters.Add("pOfficeDesc", OracleType.Char, 128);
cmd.Parameters["pOfficeDesc"].Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
var pOfficeDesc = Convert.ToString(cmd.Parameters["pOfficeDesc"].Value);
messagebox.show(pOfficeDesc);
}
}
You need to set CommandType to StoredProcedure - like that:
cmd.CommandType = CommandType.StoredProcedure;
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
MySQL database to combo box using mysqldatareader in c#.net
MySqlCommand cmd = new MySqlCommand("select * from product", connection);
MySqlDataReader dread = cmd.ExecuteReader();
while (dread.Read())
{
}
using mysqldatareader not a mysqldataadapter.
Wow...
Suppost your combox name is cbProducts, and you want fill it with the colum "description" of the query
MySQL database to combo box using mysqldatareader in c#.net
MySqlCommand cmd = new MySqlCommand("select * from product", connection);
MySqlDataReader dread = cmd.ExecuteReader();
while (dread.Read())
{
cbProducts.Items.Add(dread("description");
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Okay, I am wanting to basically connect my windows form application in C# to my database, what I want it to do is display a random word from the database into the label of my form. When I say display a random word I mean display a random word from the 20 words in a table of my database. I was wondering how would you do this? I really dont want the answer as I want to learn, but could you explain how would I do this?
Thanks in advance:)
I am wanting to connect the database using Access rather than the framework provided by .NET
First of all I would like to suggest to use google first Beginners guide to connect SQL with C# then I would like you to post question regarding to one topic for instance - Connect SQL with C#. And the part with picking random word should be another solo question.
Anyway I hope this will work for you, but please, keep in mind that we are not here to code for you without any coding effort and your code.
My code:
List<string> wordList = new List<string>();
string connection = "YourConnectionString";
OleDbConnection con = new OleDbConnection(connection);
string query = "SELECT * FROM yourTable WHERE ID=#param"; // add as many conditions as you need
OleDbCommand comm = new OleDbCommand(query, con);
comm.Parameters.AddWithValue("#param", textBox1.Text); //example of parameter
con.Open();
OleDbDataReader rdr = comm.ExecuteReader();
while (rdr.Read()) //this will loop through all rows with given conditions.
{
wordList.Add(rdr.GetString(rdr.GetOrdinal("YourSQLColumn")).Trim());
}
con.Close();
Random rnd = new Random();
int randomint = rnd.Next(1, 20); // generates a random number between 1 and 20
label1.Text = wordList[randomint].ToString();
Here's a sample to get you started
public static void Main()
{
string connectionString = "data source=.\\SQLEXPRESS;Integrated Security=SSPI;database=InsertDatabaseNameHere; connection timeout=30";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand command = new SqlCommand("select ColumnName from TableName", connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetValue(0));
}
connection.Close();
}
Just set up a SQLDataReader and convert to a list...you just have a one-dimensional list of strings. You'll be looping through the results and adding them to a list. (There's probably a more elegant way to do this, but you've only got 20 strings, not 20,000, so I don't think you need to get crazy with this)
Here's another SO question to get you started...this answer is probably what you need.
You just set your Datareader up against Access (there's a bazillion hits on doing this), convert it to a list, and off you go...
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
public bool ValidateUser(string uName)
{
SqlCommand cmd = new SqlCommand();
if (connection == null)
{
connection = connectToDB();
}
cmd.Connection = connection;
cmd.CommandText = "Select * from Users where UserName='" + uName + "'";
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.Rows.Count > 0)
{
return true;
}
else
{
return false;
}
I wrote the code in my data access layer but it was giving error on rows to count the columns.
Error:
'System.Data.SqlClient.SqlDataReader' does not contain a definition for 'Rows' and no extension method 'Rows' accepting a first argument of type 'System.Data.SqlClient.SqlDataReader' could be found (are you missing a using directive or an assembly reference?)
Use HasRows instead because SqlDataReader doesn't have a property call Rows.
if (dr.HasRows)
{
return true;
}
However, if you want the count instead you may load it into a datatable
DataTable dt = new DataTable();
dt.Load(dr);
int num = dt.Rows.Count;
SqlDataReader does not have a Rows Property.
Perhaps consider the HasRows property of SqlDataReader
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.hasrows.aspx
There is no Rows property in an SqlDataReader.
But your code has many problems.
I would change your code in this way:
public bool ValidateUser(string uName)
{
using(SqlConnection cn = connectToDB())
using(SqlCommand cmd = new SqlCommand("Select count(*) from Users where UserName=#name", cn))
{
cmd.Parameters.AddWithValue("#name", uName);
return (Convert.ToInt32(cmd.ExecuteScalar()) > 0)
}
}
The connection object is no more global and it is destroyed in
closing of the using statement.
No need to use a DataReader just to find out if the user exists or
not
Using a parameterized query to avoid SQL Injection on the input data
Avoid a global connection object. There is the connection pooling infrastructure that removes any performance problem and you are safe from excessive resource usage.
The SqlDataReader is a good choice when you need to retrieve sequentially a lot of records, but to get just the information if the user exists or not the best approach is through the ExecuteScalar method and an appropriate sql.
The parameterized query is a must for every serious database work. It will pass the work to format your input to the framework and you don't risk an Sql Injection
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
This method below goes into a table and deletes all of the table. But in the datatable "table" below in the first column there are dates which i would like to be deleted from the database. how would i go about doing this
Datatable table = new DataTable()
string sqlConnectionString =
"Server = 100.720.8.196; Database = testDat; User Id = sa; Password = ";
// Copy the DataTable to SQL Server
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
{
string deleteSting =
"delete from dbo.testTable where clientId=1212";
conn.Open();
using (SqlCommand cmd = new SqlCommand(deleteSting, conn))
{
cmd.ExecuteNonQuery();
}
conn.Close();
}
I'm just guessing here, you probably mean to make the date column empty. If that's the case then you use UPDATE, like:
string updateString =
"UPDATE dbo.testTable SET datecol = #datecol where clientId=#clientID";
conn.Open();
using (SqlCommand cmd = new SqlCommand(updateString, conn))
{
cmd.Parameters.Add("#datecol", SqlDbType.Date).Value = DbNull.Value;
cmd.Parameters.Add("#clientID", SqlDbType.Int).Value = 1212;
cmd.ExecuteNonQuery();
}
conn.Close();
Well, there are a few options. You could loop through your table and create a string containing your dates in a comma separated list. With that, you can create a SQL Statement like delete from table where dateCol in (date1, date2, date3, etc...)
Or you could just loop through your data table, and do one delete per loop iteration. Either way will work.
However you decide to proceed, make sure to use parameters instead of string concatenation to prevent issues like SQL Injections:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx