I want to fetch the maximum value of date from the table. But I always get an 'OutofRangeException' error. I changed my query several times.
Due_Date column has date data type
Due_Date_Sample is a string var
Due_Date_var is a DateTime var
My code:
using (SqlConnection sqlCon = new SqlConnection(Main.connectionString))
{
string commandString = "SELECT TOP 1 FORMAT(Due_Date,'dd-MM-yyyy') FROM Transactions WHERE Plot_Code='" + Plot_Code_var + "' ORDER BY Due_Date DESC;";
SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);
sqlCon.Open();
SqlDataReader dr = sqlCmd.ExecuteReader();
while (dr.Read())
{
date_control_var = 2;
Due_Date_Sample = (dr["Due_Date"].ToString());
Due_Date_var = DateTime.Parse(Due_Date_Sample.ToString());
}
dr.Close();
}
You need to give an alias to the selected value, e.g.: FORMAT(Due_Date,'dd-MM-yyyy') as Due_Date
You can do this:
using (SqlConnection sqlCon = new SqlConnection(Main.connectionString))
{
string commandString = "SELECT TOP 1 FORMAT(Due_Date,'dd-MM-yyyy') as Due_Date FROM Transactions where Plot_Code='" + Plot_Code_var + "' ORDER BY Due_Date DESC;";
SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);
sqlCon.Open();
SqlDataReader dr = sqlCmd.ExecuteReader();
while (dr.Read())
{
date_control_var = 2;
Due_Date_Sample = (dr["Due_Date"].ToString());
Due_Date_var = DateTime.Parse(Due_Date_Sample.ToString());
}
dr.Close();
}
Related
Error while using NextResult fuction with datareader
cannot get second table result and error on second NextResult line
"
invalid attempt to call nextresult when reader is closed
"
using (SqlConnection myCon = DBCon)
{
try
{
string Qry = #"SELECT [OPSProcedure],[OPSInsertedOn],[OPSInsertedBy]
FROM [Operation] where OPSID = '" + opId + "';";
Qry += #"SELECT LKCPID FROM dbo.ConcurrentProcedure where CPOperationID = '" + opId + "';";
Qry += #"SELECT IOperaitonID FROM dbo.LkupIntraOperativeAdverseEvents where IOperaitonID = '" + opId + "';";
myCon.Open();
SqlCommand myCommand = new SqlCommand(Qry, myCon);
myCommand.CommandType = CommandType.Text;
SqlDataReader sqlReader = myCommand.ExecuteReader();
DataSet dr = new DataSet();
if (sqlReader.HasRows)
{
dt1.Load(sqlReader);
if(sqlReader.NextResult())
{
dt2.Load(sqlReader);
}
if (sqlReader.NextResult())
{
dt3.Load(sqlReader);
}
}
sqlReader.Close();
}
catch (Exception ex)
{
}
}
What I have tried:
i have tried using below code for multiple result
DataTable.Load closes the sqlReader if sqlReader.IsClosed is false and NextResults returns false as per this forum.
As such, instead of:
if (sqlReader.NextResult())
you need to use:
if (!sqlReader.IsClosed && sqlReader.NextResult() && sqlReader.HasRows)
In this context I would simply use an SqlDataAdapter to make one single call and fill all your tables
using (SqlConnection myCon = DBCon)
{
try
{
string Qry = #"SELECT [OPSProcedure],[OPSInsertedOn],[OPSInsertedBy]
FROM [Operation] where OPSID = #id;
SELECT LKCPID FROM dbo.ConcurrentProcedure
where CPOperationID = #id;
SELECT IOperaitonID FROM dbo.LkupIntraOperativeAdverseEvents
where IOperaitonID = #id";
myCon.Open();
SqlDataAdapter da = new SqlDataAdapter(Qry, myCon);
da.SelectCommand.Parameter.Add("#id", SqlDbType.NVarChar).Value = opID;
DataSet ds = new DataSet();
da.Fill(ds);
// Test...
Console.WriteLine(ds.Tables[0].Rows.Count);
Console.WriteLine(ds.Tables[1].Rows.Count);
Console.WriteLine(ds.Tables[2].Rows.Count);
Notice also that you should never concatenate strings to build sql commands. Always use parameters.
I have the following code
public class dthvendas: System.Web.Services.WebService {
public class typVenda
{
//public string campanha;
public string id;
public string contact_moment;
public string nome;
// few more properties
}
[WebMethod][SoapDocumentMethod]
public typVenda getListaVendas(string dt_min, string dt_max)
{
//venda vendas = new List<venda>();
typVenda objVenda = new typVenda();
SqlConnection con = new SqlConnection(#"Data Source=server;Initial Catalog=database;User ID=user;password=password");
//SqlCommand cmd = new SqlCommand("SELECT * FROM dbo where contact_moment >='" + dt_min + "' AND contact_moment <DATEADD(dd, 1, '" + dt_max + "')", con);
SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.vcnosadesoes_getlistavendas", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
//var objVenda = new typVenda();
//objVenda.campanha = dr["id"].ToString();
objVenda.id = dr["id"].ToString();
objVenda.contact_moment = dr["contact_moment"].ToString();
objVenda.nome = dr["nome"].ToString();
objVenda.pacote = dr["pacote"].ToString();
objVenda.telefone = dr["telefone"].ToString();
objVenda.codigo_wc = dr["codigo_wc"].ToString();
//vendas.Add(objVenda);
}
dr.Close();
}
con.Close();
return objVenda;
//return vendas.ToArray();
}
The problem is that is only returning the first row instead of all rows from the table. What could be the problem any ideas?
Also when i return it says "This XML file does not appear to have any style information associated with it. The document tree is shown below." It should have a header like this:
<?xml version="1.0" encoding="UTF‐8" ?>
If you have n fetched rows available in the reader, probably you will get the last row, since the created object's properties ware over writted in each iteration of the while (dr.Read()) and finally return the latest value to the calling method. You should re-define your method to return List<typVenda>, and hence populate the list with objects constructed in each iteration. and finally return the list at the end of iteration.
Few more suggestions For you to improve the Code:
Make use of using while dealing with SqlConnection and SqlCommand; since you need not to bother about the close connection and disposing commands etc. using will take care of these things
Need not to check the reader has rows or not (if (dr.HasRows)) use while (dr.Read()) will not execute the enclosed statements if there are no rows.
Now consider the following code:
public List<typVenda> getListaVendas(string dt_min, string dt_max)
{
List<typVenda> objVendaList = new List<typVenda>();
using (SqlConnection con = new SqlConnection("connection String here"))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.vcnosadesoes_getlistavendas", con))
{
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
var objVenda = new typVenda();
// Assign the values to the properties here
objVendaList.Add(objVenda);
}
dr.Close();
}
}
return objVendaList;
}
public List<typVenda> getListaVendas(string dt_min, string dt_max)
{
venda vendas = new List<typVenda>();
typVenda objVenda = new typVenda();
SqlConnection con = new SqlConnection(#"Data Source=server;Initial Catalog=database;User ID=user;password=password");
//SqlCommand cmd = new SqlCommand("SELECT * FROM dbo where contact_moment >='" + dt_min + "' AND contact_moment <DATEADD(dd, 1, '" + dt_max + "')", con);
SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.vcnosadesoes_getlistavendas", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
var objVenda = new typVenda();
//objVenda.campanha = dr["id"].ToString();
objVenda.id = dr["id"].ToString();
objVenda.contact_moment = dr["contact_moment"].ToString();
objVenda.nome = dr["nome"].ToString();
objVenda.pacote = dr["pacote"].ToString();
objVenda.telefone = dr["telefone"].ToString();
objVenda.codigo_wc = dr["codigo_wc"].ToString();
vendas.Add(objVenda);
}
dr.Close();
}
con.Close();
return vendas;
}
How can I get the ID against the selected value of a DropDownList which is bound with DB?
Then how can I insert this ID into another table?
To get ID code
string query = "Select ID From Table-1 Where Name=" + DropDwonList.SelectedValue;
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
string getId = dr[0].ToString();
DropDownList Binding Code
string query = "Select ID, Name from Table-1";
SqlConnection con = new SqlConnection(conStr);
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
da.Fill(dt);
DropDwonList.DataSource = dt;
DropDwonList.DataTextField = "Name";
DropDwonList.DataValueField = "ID";
DropDwonList.DataBind();
DropDwonList.Items.Insert(0, new ListItem("--Select Name--"));
1) string Id = DropDwonList.SelectedValue;
2) To insert into another table just use a query:
string Id = DropDwonList.SelectedValue;
using (SqlConnection sql = new SqlConnection("Your connection string"))
{
SqlCommand cmd = new SqlCommand();
string query = #"INSERT INTO TABLE2(Column1)
VALUES(" + Id + ")";
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.Connection = sql;
sql.Open();
cmd.ExecuteNonQuery();
sql.Close();
}
You should do it this way because you always ensure that you are closing a connection after using it.
I'm trying to display the SQL query result in a label but it's not showing. This is my code:
string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID = '" + ID.Text + "' ";
SqlCommand showresult = new SqlCommand(result, conn);
conn.Open();
showresult.ExecuteNonQuery();
string actresult = ((string)showresult.ExecuteScalar());
ResultLabel.Text = actresult;
conn.Close();
Need help please. Thanks!
Try this one.
string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID = '" + ID.Text + "' ";
SqlCommand showresult = new SqlCommand(result, conn);
conn.Open();
ResultLabel.Text = showresult.ExecuteScalar().ToString();
conn.Close();
Is there a typo in there? You have two calls to the database:
showresult.ExecuteNonQuery();
This won't return a value and I'm not sure why you would have it there
string actresult = ((string)shresult.ExecuteScalar());
Unless you have a shresult variable, this query should error. What is the shresult variable?
Use SqlParameter to filter the result and call ExecuteScalar() or ExecuteReader() method.
string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID=#ID";
SqlCommand showresult = new SqlCommand(result, conn);
// If ID is int type
showresult.Parameters.Add("#ID",SqlDbType.Int).Value=ID.Txt;
// If ID is Varchar then
//showresult.Parameters.Add("#ID",SqlDbType.VarChar,10).Value=ID.Txt;
conn.Open();
string actresult = (string)showresult.ExecuteScalar();
conn.Close();
if(!string.IsNullOrEmpty(actresult))
ResultLabel.Text = actresult;
else
ResultLabel.Text="Not found";
using (SqlConnection conn = new SqlConnection(connectionString))
{
string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID = #id";
SqlCommand showresult = new SqlCommand(result, conn);
showresult.Parameters.AddWithValue("id", ID.Text);
conn.Open();
ResultLabel.Text = showresult.ExecuteScalar().ToString();
conn.Close();
}
This will dispose the connection and has no string concatenation in the query.
conn.Open();
string result = "SELECT ACTIVE FROM test WHERE ID = '" + ID.Text + "' ";
SqlCommand showresult = new SqlCommand(result, conn);
showresult.ExecuteNonQuery();
int actresult = ((int)showresult.ExecuteScalar());
ResultLabel.Text = actresult.Tostring();
conn.Close();
I wrote some code that takes some values from one table and inserts the other table with these values.(not just these values, but also these values(this values=values from the based on table))
and I get this error:
System.Data.OleDb.OleDbException (0x80040E10): value wan't given for one or more of the required parameters.`
here's the code. I don't know what i've missed.
string selectedItem = comboBox1.SelectedItem.ToString();
Codons cdn = new Codons(selectedItem);
string codon1;
int index;
if (this.i != this.counter)
{
//take from the DataBase the matching codonsCodon1 to codonsFullName
codon1 = cdn.GetCodon1();
//take the serialnumber of the last protein
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=C:\\Projects_2012\\Project_Noam\\Access\\myProject.accdb";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
string last= "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = "+this.name ;
OleDbCommand getSerial = new OleDbCommand(last, conn);
OleDbDataReader dr = getSerial.ExecuteReader();
dr.Read();
index = dr.GetInt32(0);
//add the amino acid to tblOrderAA
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
string insertCommand = "INSERT INTO tblOrderAA(orderAASerialPro, orderAACodon1) "
+ " values (?, ?)";
using (OleDbCommand command = new OleDbCommand(insertCommand, connection))
{
connection.Open();
command.Parameters.AddWithValue("orderAASerialPro", index);
command.Parameters.AddWithValue("orderAACodon1", codon1);
command.ExecuteNonQuery();
}
}
}
EDIT:I put a messagebox after that line:
index = dr.GetInt32(0);
to see where is the problem, and I get the error before that. I don't see the messagebox
Your SELECT Command has a syntax error in it because you didn't enclose it with quotes.
Change this:
string last = "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = "+this.name ;
OleDbCommand getSerial = new OleDbCommand(last, conn);
OleDbDataReader dr = getSerial.ExecuteReader();
to
string last = "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = ?";
OleDbCommand getSerial = new OleDbCommand(last, conn);
getSerial.Parameters.AddWithValue("?", this.name);
OleDbDataReader dr = getSerial.ExecuteReader();
This code is example from here:
string SqlString = "Insert Into Contacts (FirstName, LastName) Values (?,?)";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("LastName", txtLastName.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
}
Try to do the same as in the example.