Assign entered texbox value to Sql query |C#|Oracle
How do i assign the Textbox value to my SQL Query C#
In the Above Image i typed Tablename = PERSONDETAILS this entered value in textBox1.Text should be passed to my SQL Query as a Paramter.So Hard coding the table name in the SQl query will be reduced
Actual code where i want it to be Included
select dbms_metadata.get_ddl('TABLE',table_name,user) AS my_ddl from all_tables where owner ='HR' AND table_name ='PERSONDETAILS'"
code :
OracleConnection con = new OracleConnection();
con.ConnectionString = conString;
con.Open();
OracleCommand cmd = con.CreateCommand();
cmd.Parameters.Add("userid", OracleDbType.Varchar2, 20).Value = textBox1.Text.ToString();
cmd.Parameters.Add("tableName", OracleDbType.Varchar2, 20).Value = texttablename.Text.ToString();
//cmd.CommandText = "select * from all_all_tables WHERE table_name=:tableName";
cmd.CommandText ="select dbms_metadata.get_ddl('TABLE',table_name,user) AS my_ddl from all_tables where owner = :userid AND table_name = :tableName";
OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
textBox6.Text = reader.GetString(0);
}
con.Close();
You need to pass value of a textbox as a parameter to your command through Parameters property of OracleCommand.
So all you need to include in your code is:
cmd.CommandText = "select * from all_all_tables WHERE table_name=:tableName";
cmd.Parameters.Add("tableName", OracleType.VarChar, 20).Value = textBox1.Text;
Update regarding comments:
cmd.CommandText ="select dbms_metadata.get_ddl('TABLE',table_name,user) AS my_ddl from all_tables where owner = :userid AND table_name = :tableName";
// here you might want to use appropiate datatype
cmd.Parameters.Add("userid", OracleDbType.Varchar2, 20).Value = textBox1.Text;
cmd.Parameters.Add("tableName", OracleDbType.Varchar2, 20).Value = texttablename.Text;
Related
I'm trying to login to my application from my microsoft access database I'm making right now but I'm getting this error "Syntax error (comma) in query expression ('StudentID', 'Password')." Can anyone give me a fix please?
This is the code where the error is coming from:
con.Open();
string login = "SELECT (StudentID, Password) FROM Student WHERE StudentID = '"+txtStudentID+ "' and Password = '" + txtPassword + "'";
cmd = new OleDbCommand(login, con);
OleDbDataReader dr = cmd.ExecuteReader();
Take off the parentheses:
SELECT StudentID, Password FROM Student ...
And while using parameters to prevent SQL injection is very important (even if this is a school or learning project, as bad habits are hard to break), it is not the source of the problem.
You should remove the parentheses first, also using string interpolation is much better and more readable!
con.Open();
string login = $"SELECT StudentID, Password FROM Student WHERE StudentID = '{txtStudentID.text}' and Password = '{txtPassword.text}' ";
cmd = new OleDbCommand(login, con);
OleDbDataReader dr = cmd.ExecuteReader();
But the complete solution is the below and for avoiding SQL Injection you should use SQL parameters :
SqlParameter userName = new SqlParameter()
{
ParameterName = "#UserName",
DbType = DbType.String,
Direction = ParameterDirection.Input,
Value = txtStudentID.text
};
SqlParameter password = new SqlParameter()
{
ParameterName = "#Password",
DbType = DbType.String,
Direction = ParameterDirection.Input,
Value = txtPassword.text
};
SqlCommand command = new SqlCommand
{
Connection = connection,
CommandType = CommandType.Text,
CommandText = $"SELECT * FROM Student WHERE StudentID = #UserName and Password = #Password"
};
command.Parameters.Add(userName);
command.Parameters.Add(password);
con.Open();
....
I'm trying to connect my SQL Server with ASP.NET, and when I run my insert function, it displays an error.
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Insert into Table1 values('"+firstname.Text+"','"+lastname.Text+"','"+city.Text+"')";
cmd.ExecuteNonQuery();
firstname.Text = "";
lastname.Text = "";
city.Text = "";
I expect to show the inserted values but it displays this error:
System.Data.SqlClient.SqlException: 'Column name or number of supplied values does not match table definition.'
Where Id is auto incremented.
You need urgently research about SQL injection, and STOP USING string concatenation for building your SQL insert statement RIGHT NOW.
You need to use the proper technique - parametrized queries -- always - NO exceptions!
And also, it's a commonly accepted Best Practice to list the columns in your INSERT statement, to avoid trouble when tables change their columns (read more about this here: Bad habits to kick: using SELECT * / omit the column list ).
Use this code as a sample/template:
string insertQuery = #"INSERT INTO dbo.Table1 (FirstName, LastName, City)
VALUES (#FirstName, #LastName, #City);";
using (SqlCommand cmd = new SqlCommmand(insertQuery, con))
{
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar, 50).Value = firstname.Text;
cmd.Parameters.Add("#LastName", SqlDbType.VarChar, 50).Value = lastname.Text;
cmd.Parameters.Add("#City", SqlDbType.VarChar, 50).Value = city.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close()
}
You should specify the columns names. For example:
cmd.CommandText = $"Insert into Table1 ({ColumnName of firstname}, { ColumnName of lastname}, { ColumnName of city})
values({firstname.Text}, {lastname.Text}, {city.Text})";
You can better use a stored procedure - something like that:
cmd.CommandText = "your SP name";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = firstName.Text;
cmd.Parameters.Add("#LastName", SqlDbType.VarChar).Value = lastName.Text;
etc...
This question already has answers here:
Fetch scope_identity value in C# code from stored procedure in 3 tier architecture
(2 answers)
Closed 4 years ago.
I have a stored procedure that will return the SCOPE_IDENTITY() which is the ID for the row just added.
I have run the procedure from my C# application and adds the correct data to the database. What I need is for this returned value to be stored as a string in C~ so I can populate a text box in the UI.
SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlDataAdapter aa = new SqlDataAdapter("sp_insert_order", con);
aa.SelectCommand.CommandType = CommandType.StoredProcedure;
aa.SelectCommand.Parameters.Add("#customer_id", SqlDbType.VarChar, (50)).Value = comboBox1.SelectedItem;
aa.SelectCommand.ExecuteNonQuery();
con.Close();
Changed to
SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlDataAdapter aa = new SqlDataAdapter("sp_insert_order", con);
aa.SelectCommand.CommandType = CommandType.StoredProcedure;
aa.SelectCommand.Parameters.Add("#customer_id", SqlDbType.VarChar, (50)).Value = comboBox1.SelectedItem;
object oString = aa.SelectCommand.ExecuteScalar();
string myString = "";
if (oString != null)
{
myString = oString.ToString();
textBox1.Text = myString;
}
Textbox1 is still blank. :(
Ok, we're assuming your SProc is returning properly. Try assigning an output parameter as follows:
SqlConnection cnx = new SqlConnection(WebConfigurationManager.ConnectionStrings["yourConnName"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = cnx;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "testSProc";
cmd.Parameters.AddWithValue("name", "test Name");
SqlParameter outputParam = cmd.Parameters.Add("outID", SqlDbType.Int);
outputParam.Direction = ParameterDirection.Output;
object oString;
cnx.Open();
cmd.ExecuteNonQuery();
cnx.Close();
TextBox1.Text = outputParam.Value.ToString();
I am using mySQL with .net 4.5 to do typical CRUD commands.
I have an issue wit a parameter which is called 'Message' (Chat application). It seems the text inserted into the database is being cut off at 200 bytes.
I have tried multiple data types for the column. Currently it is TEXT, I have tried LONGTEXT and varchar(1000) etc; but still, it gets cut off at 200 bytes.
What is going on?
MySqlConnection conn = new MySqlConnection(ConnectionString());
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Parameters.Clear();
cmd.CommandText = "createStaffMessage";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#sessionID", sessionID);
cmd.Parameters["#sessionID"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("#chatID", chatId);
cmd.Parameters["#chatID"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("#message", message);
cmd.Parameters["#message"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("#byStaff", byStaff);
cmd.Parameters["#byStaff"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("#staffId", staffId);
cmd.Parameters["#staffId"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("#dateTimeString", DateTime.Now.ToLongTimeString() + " (NZ Time)");
cmd.Parameters["#dateTimeString"].Direction = ParameterDirection.Input;
cmd.Connection = conn;
MySqlDataReader rdr = cmd.ExecuteReader();
rdr.Read();
string[] newMessageDetails = new string[2];
newMessageDetails[0] = rdr[0].ToString();
newMessageDetails[1] = rdr[1].ToString();
conn.Close();
return newMessageDetails;
I am trying to get all the details of a User in an Access database. But i cant seem to save each columns value to a label. Here is the code i am using.
Also UserId has a value assigned to it already
string connString = (#"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=DataDirectory|HorseDB.mdb");
OleDbConnection conn = new OleDbConnection(connString);
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = #"SELECT * FROM [Users] WHERE [UserId] = #UserId ";
cmd.Parameters.AddWithValue("#UserId", UserId);
OleDbDataReader dbReader = cmd.ExecuteReader();
while (dbReader.Read())
{
accountUserIdLabel.Text = dbReader.GetValue(0).ToString();
//Will add other labels once this works
}
dbReader.Close();
conn.Close();