I have a small table (tbl_user_favs) that is meant to store user favorites. Column 1 is the user ID, and then every column after that is a slot for a selected favorite PC to be stored, denoted Slot1, Slot2.
using (SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\UserFavorites.mdf;Initial Catalog=tbl_user_favs;Integrated Security=True;Connect Timeout=30"))
{
string cmdString = ("SELECT * FROM tbl_user_favs WHERE UserID = '" + Globals.emailUID + "'");
SqlCommand cmd = new SqlCommand(cmdString, con);
cmd.Parameters.Add("#Slot1", SqlDbType.VarChar).Value = PCnum;
DataSet loginCredentials = new DataSet();
SqlDataAdapter dataAdapter;
con.Open();
//dataAdapter = new SqlDataAdapter(cmdString, con);
dataAdapter = new SqlDataAdapter(cmd);
dataAdapter.Fill(loginCredentials);
//cmd.ExecuteNonQuery();
con.Close();
}
Code executes, but it does not add the PCnum to the database next to the UserID. It should lok through the rows, find the UserID that matches the logged in user, Globals.emailUId, and add the PCnum to an open slot. Without worrying yet how to dynamically increment the Slots, why isn't this insert adding the PCnum to Slot 1? I've seen some tutorials use ExecuteNonQuery, and some use the dataAdapter, but both have the same result. I suspect there is something off with my SQL? Thank you
There are a couple things going on here.
First is that you are using "Parameters" incorrectly. It's supposed to add data to your query, not data to the database/row/column after a query has been made.
sql parameterized query in C# with string
Second, you are doing a select query, so you are only getting data from the db, not putting data into it.
To do what you want, you'd need to do this instead: (I don't have a good way to test this, so it may need tweaks, but it should be close.)
using (SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\UserFavorites.mdf;Initial Catalog=tbl_user_favs;Integrated Security=True;Connect Timeout=30"))
{
string cmdString = ("UPDATE tbl_user_favs SET Slot1 = #Slot1 WHERE UserID = #EmailUID");
SqlCommand cmd = new SqlCommand(cmdString, con);
cmd.Parameters.AddWithValue("#Slot1", PCnum);
cmd.Parameters.AddWithValue("#EmailUID", Globals.emailUID);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
You no longer need the DataSet or the SqlDataAdapter.
Since you seem to be confused on what parameterization is and why to use it, check out this question, too.
And here's just some more reading on the topic in general. I used these articles as resources for this answer:
https://visualstudiomagazine.com/articles/2017/07/01/parameterized-queries.aspx
https://www.c-sharpcorner.com/UploadFile/a20beb/why-should-always-use-the-parameterized-query-to-avoid-sql-i/
I am having trouble writing my datagrid changes to the database, i am trying to type in the changes on the grid and then when Button_Add_Car is pressed i execute this code and write changes to the database but nothing is being written to the database.
private void Button_Add_Car(object sender, RoutedEventArgs e)
{
SqlConnection cn = new SqlConnection();
DataSet dt = new DataSet();
SqlDataAdapter da;
SqlCommandBuilder cmdBuilder;
cn.ConnectionString = (String.Format("Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3}", SQLFunctions.connectSQL.SQLSERVER_ID, SQLFunctions.connectSQL.SQLDatabaseName, SQLFunctions.connectSQL.SQLServerLoginName, SQLFunctions.connectSQL.SQLServerPassword));
cn.Open();
da = new SqlDataAdapter("SELECT * FROM Cars", cn);
cmdBuilder = new SqlCommandBuilder(da);
da.Fill(dt);
da.Update(dt);
cn.Close();
}
Am i on the right track using this method?
Am i using the correct SQL Query? I am confused between the SELECT/INSERT as i have found examples where people are using both to achieve what i want to do. Surely i should be using the INSERT statement.
I made my own custom SQL Command to manually insert into the database so it is in fact working:
SQLCmd("INSERT INTO Cars (Date, Time) VALUES(2014-10-10, '12:00:00')");
EDIT 1:
Thanks to marc_s i managed to achieve some sort of inserting but i believe i need to modify the value section to be inside an IF Statement which will check if it is a null or not and change value back to cr.Date and cr.Time as i am making use of a list. I am unsure of how to utilize the if statement in this way because it is currently entering blank rows, although its a step in the right direction:
CarRecord cr = new CarRecord();
carRecords.Add(cr);
SqlConnection con = new SqlConnection(String.Format(#"Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3}", SQLFunctions.connectSQL.SQLSERVER_ID, SQLFunctions.connectSQL.SQLDatabaseName, SQLFunctions.connectSQL.SQLServerLoginName, SQLFunctions.connectSQL.SQLServerPassword));
con.Open();
SqlCommand comm = new SqlCommand("INSERT INTO Cars VALUES (#Date, #Time)", con);
SqlDataAdapter da = new SqlDataAdapter(comm);
da.SelectCommand.Parameters.Add(new SqlParameter("#Date", SqlDbType.NVarChar)).Value = DBNull.Value;
da.SelectCommand.Parameters.Add(new SqlParameter("#Time", SqlDbType.NVarChar)).Value = DBNull.Value;
da.SelectCommand.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlCommandBuilder builder = new SqlCommandBuilder(da);
da.Update(dt);
con.Close();
lets take your first code example.
take a look at the last 3 lines, first thing you do is to copy data from the table Cars and store that into the DataSet named dt.
then immediately after you store this dataset back into the database, without actually doing any changes.
if dot net is smart enough it wont do anything, since you didn't change anything between the fill and the update call.
what you probably should be doing is get the dataset from the datagrid or similar and store that one instead.
or do as you have started on in your second example of when you identity that a row is updated take the data from that row and construct an insert (or update) query to the database.
Can someone tell me how i can set the object reference to an instance? ....
Here, user_id is the parameter which takes a textbox value into the sql statement.
private void button1_Click(object sender, EventArgs e)
{
OracleConnection con = new OracleConnection("Data Source=KBETEST; Persist Security Info=TRUE; User ID=dbo; Password=dbo123; Unicode=True");
DataSet ds = new DataSet();
OracleDataAdapter adap = new OracleDataAdapter();
OracleCommandBuilder b = new OracleCommandBuilder(adap);
adap = new OracleDataAdapter("insert into banks_ben_branch_99 (ben_bank_id, ben_brn_code, brn_name,ben_brn_addr1, ben_brn_loc, ben_brn_state, ben_brn_city, ben_bank_city, coun_code,brn_stat, remarks, brn_id, user_id, pc_tcp_ip, rtgs_stat, pay_brn_code,sys_date) select bankid,benbrn_code,brn_name,substr(brn_addr,1,100),brn_loc, brn_stat, brn_city, brn_city, coun_code,'A', remarks, '15', :user_id,'172.20.1.109', rtgs_stat, benbrn_code,sysdate from bbbt",con);
adap.InsertCommand.Parameters.Add("user_id", OracleType.VarChar,20, "user_id").Value = textBox1.Text;
adap.Fill(ds,"A");
DataTable table = ds.Tables["A"];
dataGridView1.DataSource = ds.Tables["A"];
con.Dispose();
}
thanks!
edit
private void button1_Click(object sender, EventArgs e)
{
OracleConnection con = new OracleConnection("Data Source=KBETEST; Persist Security Info=TRUE; User ID=dbo; Password=dbo123; Unicode=True");
DataSet ds = new DataSet();
OracleDataAdapter adap = new OracleDataAdapter();
OracleCommandBuilder b = new OracleCommandBuilder(adap);
string str = "insert into banks_ben_branch_99 (ben_bank_id, ben_brn_code, brn_name,ben_brn_addr1, ben_brn_loc, ben_brn_state, ben_brn_city, ben_bank_city, coun_code,brn_stat, remarks, brn_id, user_id, pc_tcp_ip, rtgs_stat, pay_brn_code,sys_date) select bankid,benbrn_code,brn_name,substr(brn_addr,1,100),brn_loc, brn_stat, brn_city, brn_city, coun_code,'A', remarks, '15', :user_id, '172.20.1.109', rtgs_stat, benbrn_code,sysdate from bbbt";
con.Open();
adap.InsertCommand = new OracleCommand(str, con);
adap.InsertCommand.Parameters.Add("user_id", OracleType.VarChar,20).Value = textBox1.Text;
adap.InsertCommand.ExecuteNonQuery();
con.Dispose();
}
thanks everyone for your help!! i got it!
EDIT: There are multiple things wrong with your code:
You're not specifying the user_id parameter in the command, although it's in the SQL
You're trying to use the InsertCommand of the adapter even though you haven't specified any insertion SQL
You're trying to fill a dataset, but you haven't specified a query - just an insert command.
I suspect you shouldn't be using a data adapter at all. If you just need to insert some data, use:
using (var connection = new OracleConnection(...)
{
connection.Open();
string sql = "insert into banks_ben_branch_99 [... as before ...]";
using (var command = new OracleCommand(sql, conn))
{
command.Parameters.Add("user_id", OracleType.VarChar, 20)
.Value = textBox1.Text;
command.ExecuteNonQuery();
}
}
I suspect adap.InsertCommand is null in the following line:
adap.InsertCommand.Parameters.Add
On the previous line you use the following constructor:
adap = new OracleDataAdapter("insert into ...", con);
but this constructor initializes the SelectCommand, not the InsertCommand. Therefore adap.InsertCommand will still have its default value, null.
Your code then goes on to attempt to fill a DataTable using this adapter:
adap.Fill(ds,"A");
but this won't work either: you need a SelectCommand to do this.
To fill a DataSet, your code should probably look something like:
adap = new OracleDataAdapter("SELECT ... FROM ... WHERE ...", con);
adap.SelectCommand.Parameters.Add(... any parameters you need ...);
adap.Fill(ds, "A");
it is passing the break point now, no changes has been made to the oracle database tables! why is this happening.
I think you're misunderstanding how DataAdapters work.
To get data from the database into your DataTable, you need to:
Create an adapter with a SelectCommand
Call adapter.Fill to execute the SelectCommand and fill the DataTable with the result
To insert data into the database from your DataTable, you need to:
Insert a row into your DataTable with the data you want to insert
Create an adapter with an InsertCommand
Call adapter.Update to insert the data into the database.
Updating / Deleting rows in the database is similar to inserting, but uses UpdateCommand and DeleteCommand.
I think user_id is not a nullable column and it occurs when your parameter is empty. First thing is, parameter name does not match. After that, it still can happen when textbox is empty. It is better to check on client side for validation.
The parameter that you have given is null.
C# visual studio 2012 professional asp.net
I have a table containing usernames: Josh, Jeremy, Jared, Justin...
And I created a web page gridview that shows the entire table but I only want it to show Justin and nothing else.
How do I do this?
Here's some code that didn't work:
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
SqlDataReader rs;
con.Open();
SqlParameter uName = new SqlParameter("paramFName", Account.Text);
cmd.Parameters.Add(uName);
cmd.CommandText = "SELECT * FROM Transactions WHERE FName=#paramFName";
rs = cmd.ExecuteReader();
cmd.Parameters.Clear();
rs.Close();
Am I supposed to create a view of the table? I tried but wasn't successful.
tips?
You simply missed the "#" at the parameter name:
SqlParameter uName = new SqlParameter("#paramFName", Account.Text);
In case of your where-clause this has the effect that you didn't provide anything for the specified parameter which simply let the query provider ignore this condition, which results in the effective query SELECT * FROM Transactions.
Beside you should think about using the using block:
using (SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True"))
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM Transactions WHERE FName=#paramFName";
cmd.Parameters.AddWithValue("#paramFName", Account.Text);
con.Open();
using (var rs = cmd.ExecuteReader())
{
//ToDo: Do something with the reader.
}
}
And another hint: If you need to fill up a DataTable with the result, you can use a SqlDataAdapter instead of using the data reader:
using (var adapter = new SqlDataAdapter(cmd))
{
var dataTable = new DataTable();
dataTable.TableName = "QueryResult";
adapter.Fill(dataTable);
return dataTable;
}
If you are trying to select the first 10 names for example then you need to change your SQL Select to the following:
cmd.CommandText = "SELECT TOP 10 * FROM Transactions WHERE FName=#paramFName";
Is that what you were after?
EDIT
OK so you are not actually displaying your data anywhere which is the actual problem.
You need to create a datatable and display it in a gridview.
Check out the following links for examples:
Gridview examples
MSDN Gridview examples
Your code seems fine, although you do not provide much information.
If you're using SQL Server 2012 have a look at the keywords OFFSET and FETCH.
For earlier versions you need to use ROW_NUMBER OVER PARTITION
As a good practice you should always limit the number of elements returned.
I'm working with C# and SQL Sever 2008, when I try to create a command for searching a record I got exception that said "Invalid Column name"
this is my code :
void cari()
{
koneksi.Open();
DataTable dt = new DataTable();
SqlDataAdapter SDA = new SqlDataAdapter("SELECT * FROM jadwalkuliah where Subject = "+ textBox1.Text, koneksi);
SDA.Fill(dt);
koneksi.Close();
dataGridView1.DataSource = dt;
}`
the search command should be work as search engine, can anyone help me?
Well the immediate problem is that your WHERE clause will look something like:
where Subject = Foo
which is trying to compare the value of the Subject column with the value of the Foo column.
The hacky way of fixing this is to put quotes round the value. The better solution is to use parameterized SQL:
string sql = "SELECT * FROM jadwalkuliah where Subject = #Subject";
using (SqlConnection connection = new SqlConnection(...))
using (SqlDataAdapter adapter = new SqlDataAdapter(sql, connection))
{
connection.Open();
adapter.SelectCommand.Parameters.Add("#Subject", SqlDbType.VarChar)
.Value = textBox1.Text;
adapter.Fill(dt);
}
Additionally, note that you shouldn't be performing database accesses from a GUI thread. It's not clear whether this is a web app (in which case it's okay) or WPF/WinForms (in which case it's not).
Note that that will still try to make an exact match. For a "wildcard" match you'll need to change it to something like:
SELECT * FROM jadwalkuliah where Subject LIKE #Subject
... and add the parameter with something like "%" + textBox1.Text + "%". (You'll need to then think about escaping within that value, but that's another matter...)
You haven't quoted the value of subject:
SqlDataAdapter SDA = new SqlDataAdapter("SELECT * FROM jadwalkuliah where Subject = '"+ textBox1.Text + "'",
koneksi);
Or for a contains search:
SqlDataAdapter SDA = new SqlDataAdapter("SELECT * FROM jadwalkuliah where Subject = '%"+ textBox1.Text + "%'", koneksi);
You shouldn't build queries this way. It is susceptible to SQL injection attacks.