I am trying to access a table in Visual Studio 2012 and am using Oracle 11g as the back end.
This is my code part which is giving error:
comm = new OracleCommand();
comm.Connection = conn;
comm.CommandText = "select * from message where send_username='" + username + "' or r_username='"+username+"' order by id desc";
ds = new DataSet();
da = new OracleDataAdapter(comm.CommandText, conn);
da.Fill(ds, "message");
dt = ds.Tables["message"];
The same query when i run in SQL Command Prompt, it gives me 3 tuples as output but in this it is giving error
There is no row at position 1.
It is only giving one particular row as output no matter whatever else i do.
Any idea what I am doing wrong ??
if (ds.Tables.Count > 0 )
{
dt = ds.Tables["message"];
}
And
if (ds.Tables["message"].Rows.Count > 0)
{
}
Related
I try am trying to build a function that populates a table when given the name of the table and what parameter to order it by.
I think I am just making a syntax error in my SQL command but I can't find it. Please help.
public DataTable populateTable(string tableName, string orderByParameter)
{
DataTable table = new DataTable();
string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
string cmdString = "SELECT * FROM (value = #tbl) ORDER BY (parameter = #obp) DESC";
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = cmdString;
cmd.Parameters.AddWithValue("#tbl", tableName);
cmd.Parameters.AddWithValue("#obp", orderByParameter);
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
ad.Fill(table);
}
}
try
{
GridView1.DataSource = table;
GridView1.DataBind();
return table;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
}
}
You can't have variables in table name or in 'order by' clause.
You could build the query dynamically as:
string cmdString = "SELECT * FROM [" + tableName + "] ORDER BY " + orderByParameter +" DESC";
With this you won't need to add the parameters #tbl and #obp to the command.
Note that this runs into SQL injection related vulnerabilities. So you shouldn't do this unless you are absolutely certain that the table with given name exists, and the orderByParameter is a valid expression.
I have the following code that runs on a button click:
protected void Button2_Click(object sender, EventArgs e)
{
String str = "SELECT * " +
"FROM ConcernTicket INNER JOIN Employee " +
"ON ConcernTicket.EmployeeReportedToID = Employee.EmployeeId " +
"WHERE (Employee.FirstName LIKE '%' + #search2 + '%')";
SqlCommand xp = new SqlCommand(str, vid);
xp.Parameters.Add("#search2", SqlDbType.NVarChar).Value =
TextBox1.Text;
vid.Open();
xp.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = xp;
DataSet ds = new DataSet();
da.Fill(ds, "Employee.FirstName");
GridView2.DataSource = ds;
GridView2.DataBind();
vid.Close();
}
The problem I am facing is that the search runs with no errors but instead of just returning the results where the FirstName variable matches, it displays all current Concern Tickets. I am assuming it is a fairly simple fix with the SELECT statement, but for some reason I have not been able to figure out what is going wrong. I just started working with sql so I apologize that I am having such a silly issue, any help would be appreciated, thanks!
Check that TextBox1.Text is not empty. If it is empty, the query will be:
WHERE (Employee.FirstName LIKE '%%')";
Also check that #search2 is being replaced properly. The + operator is not what you would expect in MySQL. Perhaps this is what you're looking for:
"WHERE (Employee.FirstName LIKE '%#search2%')";
Hope that helps
your problem is not the SQL query. In fact you use ExecuteNonQuery() to extract select result. ExecuteNonQuery() just returns a single integer.Please use a code like this and let me know if the problem persists.
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
adapter.SelectCommand = new SqlCommand("Your SQL Statement Here", connection);
adapter.Fill(ds);
connection.Close();
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show(ds.Tables[0].Rows[1].ItemArray[1].ToString());
}
}
I need to add one more column in gridview as difference of Supplier_Quantity - Store_quantity and that difference should be stored in new column after the supplier_Quantity.
But, when I click on Calculate button column what should I do then ?
I tried the following query:
select
Product_Name, Supplier_Quantity, Store_Quantity,
'DIFFRENCE' = Supplier_Quantity - Store_Quantity
from
relatesupp
but it shows in sql only and as soon as I use it in Visual Studio it doesn't show in gridview.
You can place the code in the button and get the desired result in the datagridview :
string sQuery = "select Product_Name, Supplier_Quantity, Store_Quantity, Supplier_Quantity - Store_Quantity As 'DIFFRENCE' "
+"from relatesupp";
SqlCommand cmd = new SqlCommand(sQuery, con);
SqlDataReader sdr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(sdr);
dataGridView1 .DataSource = dt;
Is it possible to use parameters together with NpgsqlDataAdapter, as I can do with NpgsqlCommand:
string sql = "SELECT * FROM tbl_student WHERE name = #val";
NpgsqlCommand command = new NpgsqlCommand(sql, conn);
command.Parameters.AddWithValue("#val", name);
I have this code, which displays the information about the students i a gridview:
string sql = "SELECT * FROM tbl_student WHERE studentname = '" + name + "'";
DataSet ds = new DataSet();
DataTable dt = new DataTable();
NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn);
ds.Reset();
da.Fill(ds); // filling DataSet with result from NpgsqlDataAdapter
dt = ds.Tables[0]; // select select first column
GridView1.DataSource = dt; //connect grid to DataTable
GridView1.DataBind();
My question is: can I somehow use parameters (as in the example above) instead of using '" + name + "' in the SQL?
I have learned always to use parameters, is it also necessary when using NpgsqlDataAdapter?
Thank you.
I used to have the same question and this is what I came up with:
string sql = "SELECT * FROM tbl_student WHERE studentname = #param";
NpgsqlCommand command = new NpgsqlCommand(sql,conn);
command.Parameters.Add("#param", textBox_studentname.Text); //add the parameter into the sql command
DataTable dt = new DataTable();
//load the DataReader object of the command to the DataTable
dt.Load(NpgsqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection));
GridView1.DataSource = dt;
You could read this and this.
hii,can anyone tell what is wrong with this code.??
SqlCommand command = new SqlCommand("SELECT DISTINCT TOR_Name FROM TESTCASESTATUS_TABLE WHERE TestCaseID = '"
+ DropDownList1.SelectedItem.Text + "'", connection);
SqlDataReader x = command.ExecuteReader();
if (null != x && x.HasRows)
TestCaseName.Text = Convert.ToString(x["TOR_Name"]);
else
TestCaseName.Text = "something";
x.Close();
when i debug the code it is even getting into the if conditioon but then it is throwing an error, invalid attempt to read data when no data is present. !!!
please help/.
You need to issue a DataReader.Read command for the data to be actually loaded into fields, like
SqlDataReader x = command.ExecuteReader();
if (null != x && x.HasRows)
{
x.Read();
TestCaseName.Text = Convert.ToString(x["TOR_Name"]);
}
....
Call x.Read() to fetch the first result.