I had make this small method to insert data from C# forms into my Oracle database. The code processed fine, but when I go to SQL Developer to check if the record has been inserted or not, I found nothing...
public void conn2db()
{
try
{
string connstring = "data source=test_db;user id=system;password=password;";
string statmentcmd = "insert into register_user (userid,username,pass,fullname,phonenum,gender,country) values (" + 1 + "," + textBox1.Text + "," + textBox2.Text + "," + textBox4.Text + "," + textBox5.Text + "," + radioButtonValue+ ","+comboBox1.Text+");";
OracleConnection conn = new OracleConnection(connstring);
conn.Open();
MessageBox.Show("connected to database");
OracleCommand cmd = new OracleCommand();
cmd.CommandText=statmentcmd;
cmd.Connection=conn;
OracleDataAdapter oda = new OracleDataAdapter(cmd);
MessageBox.Show(statmentcmd);
conn.Close();
MessageBox.Show("Connection closed");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Try executing the command like this:
OracleCommand cmd = new OracleCommand();
cmd.CommandText = statmentcmd;
cmd.Connection = conn;
cmd.ExecuteNonQuery();
Or more simply:
OracleCommand cmd = new OracleCommand(statmentcmd, conn);
cmd.ExecuteNonQuery();
try change the Copy to Output Directory : Do notcopy
Related
I managed to create my own "save, update, delete" program with SQL after watching a video.
I have an issue, if I click "update" without having the "IndexNumber" in the database, nothing will happen.
Can anybody advise me on how to improve my "update" button? Perhaps if the data does not exist, the program can prompt the user with a message box instead of doing nothing. Like "IndexNumber does not exist therefore unable to update"
My update code
SqlConnection con = new SqlConnection(
#"Data Source=(LocalDB)\v11.0; AttachDbFilename=" + Application.StartupPath +
"\\GlennTeoDB.mdf; Integrated Security=True;Connect Timeout=30");
con.Open();
SqlCommand cmd = new SqlCommand(#"UPDATE GlennTeoStudents SET IndexNumber = '" +
numIN.Value + "',Name = '" + txtName.Text + "',Age ='" + txtAge.Text +
"',HandPhoneNumber = '" + txtHP.Text + "',GPA = '" + numGPA.Value +
"' WHERE (IndexNumber='" + numIN.Value + "')", con);
cmd.ExecuteNonQuery();
con.Close();
SqlCommand.ExecuteNonQuery() returns the number of rows affected (int).
You could check on the return value:
SqlCommand.ExecuteNonQuery(asd)
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0; AttachDbFilename=" + Application.StartupPath + "\\GlennTeoDB.mdf; Integrated Security=True;Connect Timeout=30");
con.Open();
int rowsAffected = cmd.ExecuteNonQuery();
con.Close();
if (!(rowsAffected > 0))
{
throw new ArgumentException(<Your Message>);
}
Then just catch the exception wherever you call the method and display your messagebox with
MessageBox.Show(<Your Message>)
try
{
.....
con.Open();
SqlCommand cmd = new SqlCommand(#"Select count(*) from GlennTeoStudents
WHERE (IndexNumber='" + numIN.Value + "')", con);
int count1 = cmd.ExecuteScalar();
if (count1 != 0)
{
do your update
}
else
{
give your message box
}
}
I have created a sql server database in godaddy and created a table named property manually.i also successfuly connected my application to the database using connection string.But i am unable to insert any values to the table using my c# code
Below is my C# code
string strQuery = "INSERT INTO property(name,email,phone,heading,description,location,image1,image2,image3,image4) VALUES('" + name + "','" + email + "','" + phone + "','" + title + "','" + description + "','" + district + "',#data,#data2,#data3,#data4);";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#data", SqlDbType.Binary).Value = bytes;
cmd.Parameters.Add("#data2", SqlDbType.Binary).Value = bytes2;
cmd.Parameters.Add("#data3", SqlDbType.Binary).Value = bytes3;
cmd.Parameters.Add("#data4", SqlDbType.Binary).Value = bytes4;
SqlConnection con = new SqlConnection(constr);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
Parameterize your query and clean it up a bit. Hope this helps.
using (SqlConnection con = new SqlConnection("Connection Info"))
{
// Create your parameterized command.
SqlCommand cmd = new SqlCommand("INSERT INTO [property] (name, email, phone, heading, description, location, " +
" image1, image2, image3, image4) VALUES " +
" (#name, #email, #phone, #heading, #description, #location, " +
" ,#image1,#image2,#image3,#image4)", con);
using (cmd)
{
// Set your command type.
cmd.CommandType = CommandType.Text;
// Add your parameters.
cmd.Parameters.AddWithValue("#name", "nameParamHere");
cmd.Parameters.AddWithValue("#email", "emailParamHere");
// and so on until you complete all params.
// Execute your command.
using (SqlDataReader dr = cmd.ExecuteReader()) { };
}
}
Try granting insert to your connection string "USER ID". See this link for more info...
http://beginner-sql-tutorial.com/sql-grant-revoke-privileges-roles.htm
GRANT INSERT
ON [property]
TO {user_name}
[WITH GRANT OPTION];
I add data from a text to excel with insert into, but it's always show string format. I want it float format(0.2, 1, 20) and I cant change them in excel (for example a coloumn in one time, only it could be changed by one by for all cells). I tried tryparse or converttoint32 func. but nothing change in excel, the numbers are still in text format..
public void ExcelWrite(string date, string station_name, string station_no, string xvaluee)
{
try
{ float j;
xvaluee=xvaluee.Trim();
float.TryParse(Valuee, out j);
string szConn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C://data.xls';Extended Properties='Excel 8.0;HDR=YES'";
OleDbConnection conn = new OleDbConnection(szConn);
conn.Open();
OleDbCommand cmd = new OleDbCommand("INSERT INTO [Sayfa1$]([Station_No],[Station_Name],[Date],[Valuee]) VALUES('" + station_no + "','" + station_name + "','" + date + "','" + j + "')", conn);
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
since you adding '' for each parameter all will take as strings
use Parameters as below
using(OleDbConnection cn = new OleDbConnection(szConn ))
{
cn.Open();
OleDbCommand cmd1 = new OleDbCommand("INSERT INTO [Sayfa1$]([Station_No],[Station_Name],[Date],[Valuee]) VALUES(?,?,?,?)", cn);
cmd1.Parameters.AddWithValue("#p1", station_no );
cmd1.Parameters.AddWithValue("#p2", station_name );
cmd1.Parameters.AddWithValue("#p3",date );
cmd1.Parameters.AddWithValue("#p4", j);
cmd1.ExecuteNonQuery();
}
I tried to connect MS Access Db in C# and want to View all.
My Db connection code is show in below
String conStr= #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Administrator\Desktop\SMSGateway2\SMS.mdb;Persist Security Info=True; Jet OLEDB:Database Password=testing" ;
OleDbConnection con;
con = new OleDbConnection(conStr);
string cmdString = "select * from Temp_Order";
OleDbCommand command = new OleDbCommand(cmdString, con);
try
{
con.Open();
command.ExecuteNonQuery();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
richTextBox1.Text = "Student Name: " + reader["SenderNo"].ToString() + "\n" +
"ID: " + reader["OrgerView"].ToString() + "\n" +
"Program: " + reader["OrderTime"].ToString() + "\n" +
"Address: " + reader["Flag"].ToString();
}
}
catch (Exception readexcp)
{
throw readexcp;
}
finally
{
con.Close();
}
First remove this line command.ExecuteNonQuery(); then check SenderNo, OrgerView, OrderTime and Flag are valid column names.
i am using asp.net with C# as code behind
OleDbConnection cn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Documents and Settings\CJP\My Documents\Visual Studio 2005\WebSites\NewElligibleSoft\elligiblity.mdb;Persist Security Info=False");
cn.Open();
string sql = "UPDATE main SET s_name='"+TextBox1.Text+"',inst_code='"+DropDownList1.SelectedItem+"',ms_oms='"+Label7.Text+"',elligiblity='"+Label12.Text+"',Board='"+DropDownList5.SelectedItem+"',percentage='"+TextBox4.Text+"' WHERE elg_id = '"+DropDownList4.SelectedItem+"'";
OleDbCommand cmd = new OleDbCommand(sql, cn);
cmd.ExecuteNonQuery();
cmd.Dispose();
cn.Close();
Response.Write("alert('DATA UPDATED')");
i am getting error on
cmd.ExecuteNonQuery();
that Data type mismatch in criteria expression.
Don't code like
string connection_string="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Documents and Settings\CJP\My Documents\Visual Studio 2005\WebSites\NewElligibleSoft\elligiblity.mdb;Persist Security Info=False";
using(OleDbConnection cn = new OleDbConnection(connection_string))
{
cn.Open();
string sql = "UPDATE main SET s_name=?,inst_code=?,ms_oms=?,elligiblity=?,Board=?,percentage=?,amount=? WHERE elg_id =?";
using(OleDbCommand cmd = new OleDbCommand(sql, cn))
{
cmd.Parameters.Add(new OleDbParameter("s_name",TextBox1.Text.Trim()));
cmd.Parameters.Add(new OleDbParameter("inst_code",DropDownList1.SelectedItem.Value.ToString()));
cmd.Parameters.Add(new OleDbParameter("ms_oms",Label7.Text.ToString()));
cmd.Parameters.Add(new OleDbParameter("elligiblity",Label12.Text));
cmd.Parameters.Add(new OleDbParameter("Board",DropDownList5.SelectedItem.Value.ToString()));
cmd.Parameters.Add(new OleDbParameter("percentage",DropDownList5.SelectedItem.Value.ToString()));
cmd.Parameters.Add(new OleDbParameter(amount",DropDownList5.SelectedItem.Value.ToString()));
cmd.Parameters.Add(new OleDbParameter("elg_id",DropDownList5.SelectedItem.Value.ToString()));
cmd.ExecuteNonQuery();
cn.Close();
}
}
Response.Write("alert('DATA UPDATED')");
Remove single quotes around DropDownList4.SelectedItem. I bet your elg_id column is of type integer or something, and you're giving it a string.
Having that said, you would be really better off if you provided text of error, database table structure and maybe some other information so that people wouldn't have to read your mind.
Can you try DropDownList1.SelectedItem.Text or DropDownList1.SelectedItem.Value
This should be the same for all DropDownLists.
Also you might have to convert TextBox4 to the appropriate datatype for "percentage".
Assuming that the percentage is a Double, you'd need something like
Double.Parse(Textbox4.Text)
Lastly, if you're not sending a "string" to the query, you would be really good to remove the single quotes from those fields. That way you're not parsing the data but still sending string information.
this is de correct code
OleDbConnection cn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Documents and Settings\CJP\My Documents\Visual Studio 2005\WebSites\NewElligibleSoft\elligiblity.mdb;Persist Security Info=False");
cn.Open();
string sql = "UPDATE main SET s_name='" + TextBox1.Text + "',inst_code='" + DropDownList1.SelectedItem.Value.ToString() + "',ms_oms='" + Label7.Text + "',elligiblity='" + Label12.Text + "',Board='" + DropDownList5.SelectedItem.Value.ToString() + "',percentage='" + float.Parse(TextBox4.Text) + "',amount='" + Label10.Text + "' WHERE elg_id = " + DropDownList4.SelectedItem.Value + "";
OleDbCommand cmd = new OleDbCommand(sql, cn);
cmd.ExecuteNonQuery();
cmd.Dispose();
cn.Close();
Response.Write("alert('DATA UPDATED')");
thanxx
OleDbConnection cn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Documents and Settings\CJP\My Documents\Visual Studio 2005\WebSites\NewElligibleSoft\elligiblity.mdb;Persist Security Info=False");
cn.Open();
string sql = "UPDATE main SET s_name='" + TextBox1.Text + "',inst_code='" + DropDownList1.SelectedItem.Value.ToString() + "',ms_oms='" + Label7.Text + "',elligiblity='" + Label12.Text + "',Board='" + DropDownList5.SelectedItem.Value.ToString() + "',percentage='" + float.Parse(TextBox4.Text) + "',amount='" + Label10.Text + "' WHERE elg_id = " + DropDownList4.SelectedItem.Value + "";
OleDbCommand cmd = new OleDbCommand(sql, cn);
cmd.ExecuteNonQuery();
cmd.Dispose();
cn.Close();
Response.Write("alert('DATA UPDATED')");