i run this and i want to fill textbox txtFname with data - but it dont do nothing
using (Conn = new SqlConnection(Conect))
{
Conn.Open();
SQL = "SELECT * FROM MEN where id = '" + txtBAR.Text.Trim() + "'";
dsView = new DataSet();
adp = new SqlDataAdapter(SQL, Conn);
adp.Fill(dsView, "MEN");
adp.Dispose();
txtFname.Text = dsView.Tables[0].Rows[3][0].ToString();
txtFname.DataBind();
Conn.Close();
}
how to do it ?
thank's in advance
using (Conn = new SqlConnection(Conect)) {
try {
// Attempt to open data connection
Conn.Open();
// Compose SQL query
string SQL = string.Format("SELECT * FROM MEN WHERE id = '{0}'", txtBAR.Text.Trim());
using(SqlCommand command = new SqlCommand(SQL,Conn)) {
// Execute query and retrieve buffered results, then close connection when reader
// is closed
using(SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection)) {
// Assign txtFname value to search value and clear value if no results returned
txtFname.Text = reader.Read() ? reader[0].ToString() : string.Empty;
reader.Close();
}
}
}
finally {
// Regardless of whether a SQL error occurred, ensure that the data connection closes
if (Conn.State != ConnectionState.Closed) {
Conn.Close();
}
}
}
However, I would advise that you
update your SQL query to return the
actual column names instead of *
replace reader[0].ToString() with
reader["FirstName"].ToString()
using (Conn = new SqlConnection(Conect))
{
Conn.Open();
SQL = "SELECT * FROM MEN where id = '" + txtBAR.Text.Trim() + "'";
SqlCommand command= new SqlCommand(SQL,Conn);
SqlDataReader reader = command.ExecuteReader()
reader.Read();
//Call Read to move to next record returned by SQL
//OR call --While(reader.Read())
txtFname.Text = reader[0].ToString();
reader.Close();
Conn.Close();
}
Edit: I just noticed 'dataSet' not database, anyway you are reading third row, is your query returns more than one row?
Related
I would like to create a variable in C# that represents the number of records of a query.
I tested the query and works correct , returning the correct value.
SELECT Count(c.Cell_ID) AS CountOfCell_ID
FROM Cells AS c
HAVING (((Exists (SELECT 1
FROM ΠΑΡΟΝΤΕΣ as cu
WHERE c.Cell_ID = cu.CellID))=False));
This returns a number only.
I would like to assign that number(result) to a variable in c#.
First step is to write the following C# code in visual studio
int: CountValue;
cnn.ConnectionString = CnnStr;
cnn.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = cnn;
string query = "SELECT Count(c.Cell_ID) AS CountOfCell_ID FROM Cells AS c HAVING(((Exists(SELECT 1 FROM ΠΑΡΟΝΤΕΣ as cu WHERE c.Cell_ID = cu.CellID)) = False));";
what should i do next to assign the value contained in query to CountValue?
What you should do next is execute the command, and read the value:
OleDbCommand command = new OleDbCommand();
command.Connection = cnn;
string query = "SELECT Count(c.Cell_ID) AS CountOfCell_ID FROM Cells AS c HAVING(((Exists(SELECT 1 FROM ΠΑΡΟΝΤΕΣ as cu WHERE c.Cell_ID = cu.CellID)) = False));";
// Open connection
cnn.Open();
// Call command's ExcuteReader
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
// Your value is here
Console.Write("OrderID :" + reader.GetInt32(0).ToString());
}
// close reader and connection
reader.Close();
cnn.Close();
The following worked for me
private void DashBoard_Load(object sender, EventArgs e)
{
// timer1.Start();
string sql = null;
sql = "SELECT Count(c.Cell_ID) AS CountOfCell_ID FROM Cells AS c HAVING(((Exists(SELECT 1 FROM ΠΑΡΟΝΤΕΣ as cu WHERE c.Cell_ID = cu.CellID)) = False));";
try
{
cnn.ConnectionString = CnnStr;
OleDbCommand command = new OleDbCommand();
command.Connection = cnn;
command= new OleDbCommand(sql, cnn);
cnn.Open();
Int32 count = Convert.ToInt32(command.ExecuteScalar());
command.Dispose();
cnn.Close();
MessageBox.Show(" No of Rows " + count);
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
A simple "select * from tablename" sql query works for a table named 'mode' but not for a table named 'user'. Why?
Both tables have 2 columns. If I run the program with the "mySQL" variable as "SELECT * FROM mode" it works fine. If I put the user table instead, which means the mySQL would have been "SELECT * FROM user" then it raises an exception which says "Syntax error in FROM clause.". How can this be?
Here is the code:
static void Main(string[] args)
{
String connectionstring = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=Accounts.mdb";
OleDbConnection conn;
conn = new OleDbConnection(connectionstring);
try
{
conn.Open();
}
catch (Exception)
{
Console.Write("Could not connect to database");
}
String mySQL = "SELECT * FROM user";
OleDbCommand cmd = new OleDbCommand(mySQL, conn);
OleDbDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.Write(String.Format("{0}\n,{1}\n", rdr.GetValue(0).ToString(), rdr.GetValue(1).ToString()));
}
Console.Read();
}
Because USER is a reserved word in MS-Access
Change you query to encapsulate it between square brakets
SELECT * FROM [User]
albeit I suggest you to change the name of the table
Do like Steve said. And a suggestion for your code:
String connectionstring = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=Accounts.mdb";
OleDbConnection conn = null;
OleDbCommand cmd = null;
OleDbDataReader rdr = null;
String mySQL = "SELECT * FROM [user]";
try
{
conn = new OleDbConnection(connectionstring);
conn.Open();
cmd = new OleDbCommand(mySQL, conn);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.Write(String.Format("{0}\n,{1}\n", rdr.GetValue(0).ToString(), rdr.GetValue(1).ToString()));
}
Console.Read();
conn.Close();
}
catch (Exception ex)
{
Console.Error.Write("Error founded: " + ex.Message);
}
finally
{
if (conn != null) conn.Dispose();
if (cmd != null) cmd.Dispose();
if (rdr != null) rdr.Dispose();
}
When I am reading data from a sql db and want to add all the items into a list (ie. eonumlist) below. Do I need to specifically assign each field or can I mass assign this data? I'm doing this for a report and want to get the data quickly. Maybe I should use a dataset instead. I have 40+ fields to bring into the report and want to do this quickly. Looking for suggestions.
public static List<EngOrd> GetDistinctEONum()
{
List<EngOrd> eonumlist = new List<EngOrd>();
SqlConnection cnn = SqlDB.GetConnection();
string strsql = "select distinct eonum " +
"from engord " +
"union " +
"select 'zALL' as eonum " +
"order by eonum desc";
SqlCommand cmd = new SqlCommand(strsql, cnn);
try
{
cnn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
EngOrd engord = new EngOrd();
engord.EONum = reader["eonum"].ToString();
engord.Name = reader["name"].ToString();
engord.Address = reader["address"].ToString();
eonumlist.Add(engord);
}
reader.Close();
}
catch (SqlException ex)
{
throw ex;
}
finally
{
cnn.Close();
}
return eonumlist;
}
I do something similar storing data from a db into a combo box.
To do this i use the following code.
public static void FillDropDownList(System.Windows.Forms.ComboBox cboMethodName, String myDSN, String myServer)
{
SqlDataReader myReader;
String ConnectionString = "Server="+myServer+"\\sql2008r2;Database="+myDSN+";Trusted_Connection=True;";
using (SqlConnection cn = new SqlConnection(ConnectionString))
{
cn.Open();
try
{
SqlCommand cmd = new SqlCommand("select * from tablename", cn);
using (myReader = cmd.ExecuteReader())
{
while (myReader.Read())
{
cboMethodName.Items.Add(myReader.GetValue(0).ToString());
}
}
}
catch (SqlException e)
{
MessageBox.Show(e.ToString());
return;
}
}
}
This connects to the database and reads each record of the table adding the value in column 0 (Name) to a combo box.
I would think you can do something similar with a list making sure the index values are correct.
Store the data as xml, then deserialize the xml to the list.
I want to retrieve the resulting value of a select statement into a string variable. Like this:
OleDbCommand cmd1 = new OleDbCommand();
cmd1.Connection = GetConnection();
cmd1.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
cmd1.ExecuteNonQuery();
I want to place the selected treatment value into a string variable. How can I do this?
Use ExecuteReader() and not ExecuteNonQuery(). ExecuteNonQuery() returns only the number of rows affected.
try
{
SqlDataReader dr = cmd1.ExecuteReader();
}
catch (SqlException oError)
{
}
while(dr.Read())
{
string treatment = dr[0].ToString();
}
Or better, use a using statement for it.
using(SqlDataReader dr = cmd1.ExecuteReader())
{
while(dr.Read())
{
string treatment = dr[0].ToString();
}
}
But if your SqlCommand returns only 1 column, you can use the ExecuteScalar() method. It returns first column of the first row as follows:-
cmd.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
string str = Convert.ToString(cmd.ExecuteScalar());
Also you can open your code to SQL Injection. Always use parameterized queries. Jeff has a cool blog article called Give me parameterized SQL, or give me death. Please read it carefully. Also read DotNetPerl SqlParameter article. SQL Injection very important when you are working queries.
Execute Scalar: Getting Single Value from the Database method to retrieve a single value (for example, an aggregate value) from a database.
cmd1.Connection = GetConnection();
cmd1.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
if(cmd.ExecuteScalar()==null)
{
var treatment = cmd.ExecuteScalar();
}
Other Way: ExecuteReader()
try
{
cmd1.CommandText ="SELECT treatment FROM appointment WHERE patientid=#patientID";
cmd1.Parameters.AddWithValue("#patientID", this.DropDownList1.SelectedValue);
conn.Open();
SqlDataReader dr = cmd1.ExecuteReader();
while (dr.Read())
{
int PatientID = int.Parse(dr["treatment"]);
}
reader.Close();
((IDisposable)reader).Dispose();//always good idea to do proper cleanup
}
catch (Exception exc)
{
Response.Write(exc.ToString());
}
the answer:
String res = cmd1.ExecuteScalar();
the remark: use parametrized query to prevent sql injection
There is a lot wrong with your example code.
You have inline sql, which opens you up to sql injection in a major way.
You are using ExecuteNonQuery() which means you get no data back.
string sSQL = "SELECT treatment FROM appointment WHERE patientid = #patientId";
OleDbCommand cmd1 = new OleDbCommand(sSQL, GetConnection()); // This may be slight different based on what `GetConnectionReturns`, just put the connection string in the second parameter.
cmd1.Parameters.AddWithValue("#patientId", text);
SqlDataReader reader = cmd1.ExecuteReader();
string returnValue;
while(reader.Read())
{
returnValue = reader[0].ToString();
}
You just need to use the ExecuteScalar method of the command - this will give you the value at the first row and column of the result set.
OleDbCommand cmd1 = new OleDbCommand();
cmd1.Connection = GetConnection();
cmd1.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
var result = cmd1.ExecuteScalar();
If your SQL statement returns more than one row/column then you can use ExecuteReader().
You need to use OleDbAdapter.
string connection = "your connection";
string query = "SELECT treatment FROM appointment WHERE patientid = " + text;
OleDbConnection conn = new OleDbConnection(connection);
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = new OleDbCommand(query, conn);
adapter.Fill(dataset);
SqlConnection dbConnect = new SqlConnection("your SQL connection string");
string name = " 'ProjectName' ";
string strPrj = "Select e.type, (e.surname +' '+ e.name) as fulln from dbo.tblEmployees e where id_prj = " + name;
SqlCommand sqlcmd = new SqlCommand(strPrj, dbConnect);
SqlDataAdapter sda = new SqlDataAdapter(strPrj, dbConnect);
ds = new DataSet();
sda.Fill(ds);
dbConnect.Open();
sqlcmd.ExecuteNonQuery();
dbConnect.Close();
I am looping through these mysql rows and processing data. But, in part of the processing I am also wanting to update into the same mysql table.
This is not working for me.
command.CommandText = "UPDATE outbox SET `faxpro` = 'DONE' WHERE `id` = '" + id + "'";
MySqlDataReader result = command.ExecuteReader();
CODE
string connString = "Server=localhost;Port=3306;Database=communications;Uid=myuser;password=mypass;";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT * FROM outbox WHERE `faxstat` = 'Y' AND `fax` <> '' AND `faxpro` = 'PENDING'";
try
{
conn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
MySqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine(reader["account"].ToString());
SendFax(reader["filepath"].ToString(), reader["filepath"].ToString(), reader["id"].ToString(), reader["fax"].ToString());
string id = reader["id"].ToString();
command.CommandText = "UPDATE outbox SET `faxpro` = 'DONE' WHERE `id` = '" + id + "'";
MySqlDataReader result = command.ExecuteReader();
}
}
I think that last command.ExecuteReader() tries to open one more reader, but it is not possible to do with one connection. Close first open reader firstly, then modify this table; or try to use command.ExecuteNonQuery() method.