Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Problem is in select query it's not working exception occur near textBox1.Text :
private void button1_Click(object sender, EventArgs e)
{
try
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * From '"+textBox1.Text+"'", con);
sda.SelectCommand.ExecuteNonQuery();
DataTable dtable = new DataTable();
sda.Fill(dtable);
BindingSource bSource = new BindingSource();
bSource.DataSource = dtable;
dataGridView1.DataSource = bSource;
sda.Update(dtable);
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Take a look at your query. Problem is you are quoting your table name and so it's considered as string literal rather a table name
"select * From '"+textBox1.Text+"'"
^... Here
Again, you are using ExecuteNonQuery() instead of ExecuteReader()
Your query is prone to SQL Injection and I don't think you can pass table name as parameter to DB. If this is your real requirement then consider using a Dynamic Query rather. A sample using s stored procedure like
create procedure usp_selectData(#tblname nvarchar(100))
as begin
declare #sql nvarchar(200);
if (exists (select * from information_schema.tables
where table_name = #tblname))
begin
set #sql = 'select * from ' + #tblname;
exec(#sql);
end
end
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
This is my code:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "data source = LAPTOP-ULT25NKH; database = college;integrated security = True";
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select * from teacher where tID = " + textBox1.Text + "";
DataSet DS = new DataSet();
SqlDataAdapter DA = new SqlDataAdapter(cmd);
DA.Fill(DS);
dataGridView1.DataSource = DS.Tables[0];
}
but I get this exception:
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: Incorrect syntax near '='."
Ensure you are properly santizing inputs and using prepared statements; to start down the line for you, try:
cmd.CommandText = "SELECT * FROM teacher WHERE tID = #tID;"
SqlParameter idParam = new SqlParameter("#tID", SqlDbType.NVarChar , 0);
idParam.Value = textBox1.Text;
cmd.Parameters.Add(idParam);
cmd.Prepare();
There are lot of issues in your existing code, I’m mentioning few points brlow.
Please move the connection string to some config file, it’s easy to maintain there.
When you have DataAdapter you don’t need to explicitly open the connection, it does that for you internally.
Please avoid * in select query, mention the columns with alias and use parameterized query to pass the parameters. Or your can write stored procedure and call it. So that I if I’m future you need to modify query, there will be no code change.
If you need to open the connection, please close it or your can use using.
You can add breakpoint and see the value of your query and if you copy this query value and run in sql server directly . This is one way to find the error in the query.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
Im trying to retrieve no of rows from sql based user input & display in gridview
Please help!
Int32 text = Convert.ToInt32(this.Txtusers.Text);
con.Open();
cmd = new SqlCommand("select TOP '" + text + "' * from Avaya_Id where LOB = '" + DDLOB.SelectedItem.Value + "' and Status = 'Unassigned'", con);
SqlDataReader rdr = cmd.ExecuteReader();
GridView1.DataSource = rdr;
GridView1.DataBind();
con.Close();
Here is how it should be written.
int text;
if(int.TryParse(this.Txtusers.Text, out text)
{
using(var con = new SqlConnection(connectionString)
{
using(var cmd = new SqlCommand("select TOP (#top) * from Avaya_Id where LOB = #LOB and Status = 'Unassigned'", con))
{
cmd.Parameters.Add("#top", SqlDbType.Int).Value = text;
cmd.Parameters.Add("#LOB", SqlDbType.Int).Value = DDLOB.SelectedItem.Value;
con.Open();
using(var rdr = cmd.ExecuteReader())
{
GridView1.DataSource = rdr;
GridView1.DataBind();
}
}
}
}
Points of interest:
Using parameters to avoid the risk of Sql Injection.
Changed Convert.ToInt32 to int.TryParse. Never trust user input.
Use the using statement for every instance that implements the IDisposable interface.
Please note that using top x without an order by clause means you get x arbitrary records from the database - since database tables are unordered by nature and the only way to ensure the order of the rows returned from a select statement is to use the order by clause.
Please note I've guessed that the second parameter is an int, if it's not, change the data type.
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 am trying to click a search button with multiple inputs on the textbox.
I have looked around and tried different methods but somehow It didn't work out. Below is the code for the click event:
private void btn_table_Click(object sender, EventArgs e) {
try {
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select [Name],[Sex],[Number] from RecordsSheet [Name] like('" + textBox1.Text + "%'),[Sex]=('" + textBox2.Text + "%'),[Number]=('" + textBox3.Text + "%'");
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
}
catch (Exception ex) {
MessageBox.Show("Error " + ex);
}
}
You are currently mixing equals and LIKE syntax on the same operations, which is going to result in some incorrectly formed queries, as well as the absence of a WHERE clause to properly use them.
Use Parameterization
If you have a specific search term, consider adding it in as a parameter with your LIKE section predefined within your query :
// Add your properties using parameters
var query = "SELECT [Name],[Sex],[Number] FROM RecordsSheet WHERE [Name] LIKE ? AND [Sex] LIKE ?,[Number] LIKE ?";
Then add your parameters along with the necessary wildcards to build your query :
OleDbDataAdapter da = new OleDbDataAdapter(command);
// Set your parameters
da.SelectCommand.Parameters.AddWithValue("p1",textBox1.Text + "*");
da.SelectCommand.Parameters.AddWithValue("p2",textBox2.Text + "*");
da.SelectCommand.Parameters.AddWithValue("p3",textBox3.Text + "*");
This approach will not only lead to resolving issues related to syntax, but it should also help keep you protected from nasty things like SQL Injection attacks.
with [Sex] and [Number] replace "=" with "like", that may help..
if not post the result description.
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
Getting the following error when tried inserting data in multiple tables.
Incorrect syntax near the keyword 'User'
Button Click Code:
private void buttonSave_Click(object sender, EventArgs e) {
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SampleTest1.Properties.Settings.SampleTestDBConnectionString"].ConnectionString);
SqlCommand cmd = conn.CreateCommand();
try {
UserId = UserId + 1;
cmd.CommandText = "INSERT INTO [User](User_Id,Name,Gender,Is_Active,Created_Date,Activated_Date) values(#userid,#name,#gender,#isactive,#createdate,#activedate)";
conn.Open();
cmd.Parameters.AddWithValue("#userid", SqlDbType.Int).Value = UserId;
cmd.Parameters.AddWithValue("#name", SqlDbType.VarChar).Value = textBoxName.Text;
cmd.Parameters.AddWithValue("#gender", SqlDbType.VarChar).Value = textBoxGender.Text;
cmd.Parameters.AddWithValue("#isactive", SqlDbType.Bit).Value = "True";
cmd.Parameters.AddWithValue("#createdate", SqlDbType.Date).Value = System.DateTime.Today;
cmd.Parameters.AddWithValue("#activedate", SqlDbType.DateTime).Value = System.DateTime.Now;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "INSERT INTO User_Details(User_Id,Mobile,Address,Job_Contract) values(#userid,#mobile,#address,#jobcontract)";
cmd.Parameters.AddWithValue("#userid", SqlDbType.Int).Value = UserId;
cmd.Parameters.AddWithValue("#mobile", SqlDbType.VarChar).Value = textBoxMobile.Text;
cmd.Parameters.AddWithValue("#address", SqlDbType.VarChar).Value = textBoxAddress.Text;
cmd.Parameters.AddWithValue("#jobcontract", SqlDbType.VarChar).Value = textBoxJobContract.Text;
cmd.ExecuteNonQuery();
conn.Close();
}
I have declared UserId value as
static int UserId = 100;
Not sure what went wrong. Please do comment if more details required.
REFERENCES:
LINK 1 : ASP.NET C# Insert data into multiple table
LINK 2 : Insert into two tables at once.
LINK 3 : Getting Syntax error in Insert statement
LINK 4 : Insert Data into two tables simultaneously in SQL Server
User is reserved keyword so you need to use it like below
Insert into [User] (columns) values (#Values);
Hope it helps!
Well, its the database design logic where I finally tried solving this problem.
I used most of the suggested edits in comments as dbo.[User], [User] and [SampleTestDB].[dbo].[User]in INSERT INTO statement.
Tried with usingstatements and changed AddWithValueto Add
Tried using a transaction query to insert into [User]table and then [User_Details]table.
Of course, tried cleaning up and rebuild the solution as I was using multiple instance and versions of Visual Studio at same time.
ISSUE:
I declared the User_Id in the [User]table as Primary,NOT NULL,Unique
and in [User_Details]table as Primary,NOT NULL and used auto-incremental index.
In the button-click code, I just used static int which conflicted the INSERT statement of [User]table as it contained Unique property.
SOLUTION:
Solved the problem by droping and recreating the [User] table with User_Id contraints same as [User_Details] table.
(Removed Unique constrain in [User] table)
This question already has answers here:
SQL : in clause in stored procedure:how to pass values
(8 answers)
Closed 7 years ago.
What I want to do :
Pass this parameter 'TV','OV','CK' as a single string into Stored Procedure (GetAllDataViaInQuery)
CREATE PROCEDURE GetAllDataViaInQuery #param varchar(240)
AS
BEGIN
SELECT TOP 100 [Model_No]
,[AppCode]
,[Model]
FROM [S_ModelMaster] where AppCode in (#param)
END
Then
I need to Pass parameter value via C# application as a single parameter.Because some time in values are may be vary.
Ex : string paramValue = "TV,OV,CK";
Then I wrote this C# code snippet.
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.Setting))
{
try
{
//hard coded parameter values
string paramValue = "TV,OV,CK";
con.Open();
DataSet ds = new DataSet();
SqlCommand com = new SqlCommand("GetAllDataViaInQuery", con);
com.CommandType = CommandType.StoredProcedure;
SqlParameter param = new SqlParameter("#param", paramValue);
com.Parameters.Add(param);
SqlDataAdapter adp = new SqlDataAdapter(com);
adp.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
But this is not work yet.
Then I execute Stored Procedure manually with SSMS.
DECLARE #return_value int
EXEC #return_value = [application].[GetAllDataViaInQuery]
#param = N'TV,OV,CK'
SELECT 'Return Value' = #return_value
But it's NOT WORKED!
Then I try it in sql query
SELECT TOP 100 [Model_No]
,[AppCode]
,[Model]
FROM [S_ModelMaster] where AppCode in ('TV','OV','CK')
And it's work.So what is the correct way to pass parameter to IN query in C#?
The way i see around this is, Use table valued parameters and send parameter in datatable format from c#.
And in Stored procedures something like select * from TableName where AppCode in(select parameter from tvpTable)
This is similar
Table valued parameters