Values from textBox not getting inserted into database - c#

This is my code for inserting into database from textfields.
SqlConnection Connection = new SqlConnection("Data Source=ESHA\\SQLEXPRESS;Initial Catalog=Gen_Lic;User ID=sa;Password=sa#");
SqlCommand Command = Connection.CreateCommand();
try
{
// Open Connection
Connection.Open();
////Console.WriteLine("Connection Opened");
// Create INSERT statement with named parameters
Command.CommandText = "INSERT INTO Gen_Lic(Lic_No, UserID, Org, UserName, SolType, Version, Lic_Type, Meap_Supp, Lic_From, Lic_To, Supp_From, Supp_To, Max_User, Max_Mach, Mach_IP, Mach_MAC) VALUES (#Lic_No, #UserID, #Org, #UserName, #SolType, #Version, #Lic_Type, #Meap_Supp, #Lic_From, #Lic_To, #Supp_From, #Supp_To, #Max_User, #Max_Mach, #Mach_IP, #Mach_MAC)";
// Add Parameters to Command Parameters collection
Command.Parameters.AddWithValue("#Lic_No", txtLNo.Text);
Command.Parameters.AddWithValue("#UserID", txtUID.Text);
Command.Parameters.AddWithValue("#Org", txtOrg.Text);
Command.Parameters.AddWithValue("#UserName", txtUName.Text);
Command.Parameters.AddWithValue("#SolType", txtSType.Text);
Command.Parameters.AddWithValue("#Version", txtVer.Text);
Command.Parameters.AddWithValue("#Lic_Type", drpLType.SelectedItem.Text);
Command.Parameters.AddWithValue("#Meap_Supp", rdoMeapSupport.SelectedValue.ToString());
Command.Parameters.AddWithValue("#Lic_From", lblLFrom.Text);
Command.Parameters.AddWithValue("#Lic_To", lblLTo.Text);
Command.Parameters.AddWithValue("#Supp_From", lblSuppFrom.Text);
Command.Parameters.AddWithValue("#Supp_To", lblSuppTo.Text);
Command.Parameters.AddWithValue("#Max_User", txtMaxUsr.Text);
Command.Parameters.AddWithValue("#Max_Mach", txtMaxMach.Text);
Command.Parameters.AddWithValue("#Mach_IP", txtMachIP.Text);
Command.Parameters.AddWithValue("#Mach_MAC", txtMachMac.Text);
Connection.Close();
}
Now the problem is the code is working fine, but the values are not getting inserted into the database. Also, when I apply a breakpoint at the starting of the connection formation, a new blank IE window opens up.
Can someone guide me where am I going wrong?

I think, you are missing the following:
Command.ExecuteNonQuery();
before the Connection.Close()

Please run this query again the database
Command.ExecuteNonQuery();
before closing the connection

Related

SQL Server INSERT statement is not executing but I am not receiving an exception either

On my button click event I want to insert a row into a table. When I click the button, I get no exception and I also don't get my messagebox to show either. I have the messagebox as a way to check to see if the query had been executed.
When I step through it skips the MessageBox and doesn't throw an exception.
private void BtnSend_Click(object sender, EventArgs e)
{
string theDate = dateTimePicker1.Value.ToString("MM-dd-yyyy");
var select = "INSERT INTO Trinity3(Date, Device_S_N, Student_Last_Name, Student_First_Name, Student_Number, School, Grade, Damage)" +
"VALUES (#Date, #Serial, #LastName, #FirstName, #StudentNum, #School, #Grade, #Damage)" +
"COMMIT";
SqlConnection connection = new SqlConnection("Data Source=CPS1113020004; Initial Catalog=Coweta Public Schools; Integrated Security=True");
// Create a SqlCommand instance
SqlCommand command = new SqlCommand(select, connection);
// Add the parameter
command.CommandType = CommandType.Text;
command.CommandText = select;
command.Parameters.AddWithValue("#Date", theDate);
command.Parameters.AddWithValue("#Serial",txtSerial.Text);
command.Parameters.AddWithValue("#LastName",txtLastName.Text);
command.Parameters.AddWithValue("#FirstName",txtFirstName.Text);
command.Parameters.AddWithValue("#StudentNum", txtStudentNum.Text);
command.Parameters.AddWithValue("#School",txtSchool.Text);
command.Parameters.AddWithValue("#Grade", txtGrade.Text);
command.Parameters.AddWithValue("#Damage", txtDamage.Text);
// Execute the query
try
{
connection.Open();
command.ExecuteNonQuery();
MessageBox.Show("Records inserted successfully");
}
catch
{
// Handle exception, show message to user...
}
finally
{
connection.Close();
}
this.Visible = false;
var searchForm = new SearchForm();
searchForm.ShowDialog();
}
You are throwing an exception but you are not seeing because there is nothing in your catch block.
Look up Try with Resources convention and always use it. This will automatically close your connection for you even if there is an exception.This is a must.
Add an exception to your catch block so you can see the error.
Your SQL string needs to have spaces after each section. When you are concatenating with "+" no extra space is created. So your query actually looks like this:
INSERT INTO Trinity3(Date, Device_S_N, Student_Last_Name, Student_First_Name, Student_Number, School, Grade, Damage)VALUES (#Date, #Serial, #LastName, #FirstName, #StudentNum, #School, #Grade, #Damage)COMMIT
Instead of writing your query in the application, you should create a stored procedure in the database that will contain all of the logic necessary to get the data. Then your application will simply call a one word stored proc instead of having a giant string representing your t-sql. ALSO you can actually test your stored proc and make sure it works without the application being involved.

SqlCommand INSERT query does not insert data into the database

I am working on Visual Studio 2013.
In the below code the MessageBox.Show("Connected to database") is shown correctly, but the SQL query is not inserting data into the database table.
When I insert data manually then it inserts without any problems. But unfortunately the data fails to insert on the button_click command.
private void DataAdd_Load(object sender, EventArgs e)
{
try
{
conn = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=Pathname;Integrated Security=True;Connect Timeout=30");
conn.Open();
MessageBox.Show("Connected to database");
cmd = new SqlCommand("INSERT INTO datains (name, dob, gender, occupation, height, weight, relation, polexpo) values('abc', '22-Aug-2001', 'Male', 'qwe2', '23', '431', 'qw23e', 'asqwed');", conn);
}
catch (Exception e1)
{
MessageBox.Show("Connection failed");
}
}
What have I done wrong here or anything I have missed?
You have forgotten to execute the query:
cmd.ExecuteNonQuery();
It is also better to close the connection after the work is done:
conn.Close();
You have to run the ExecuteNonQuery() method of your cmd to make it work, but it's also advisable to wrap both connection and command into a using statement so that they will be disposed (the connection should be also explicitly closed)

How to update Oracle CLOB column with long string using C# and Oracle Data Access Client

I'm trying to update a CLOB column in my database with a long string containing the HTML contents of an email. There are 18,000 characters in the record I'm having an issue with.
The below code will work if I set the html variable to "short string". But if I try to run the code with the long 18,000 character HTML string, I get this error: "Oracle.DataAccess.Client.OracleException ORA-22922: nonexistent LOB value ORA-02063: preceding line from ((servername))"
public static void UpdateHtmlClob(string html, string taxId,string un, string pw)
{
using (OracleConnection conn = new OracleConnection())
{
try
{
conn.ConnectionString = "User Id=" + un + ";Password=" + pw + ";Data Source=server.com;";
conn.Open();
OracleCommand cmd = new OracleCommand();
string indata = html;
cmd.CommandText = "UPDATE table1 SET HTML_BODY = :clobparam";
OracleParameter clobparam = new OracleParameter("clobparam", OracleDbType.Clob, indata.Length);
clobparam.Direction = ParameterDirection.Input;
clobparam.Value = indata;
cmd.Parameters.Add(clobparam);
cmd.Connection = conn;
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
conn.Close();
}
}
}
Before you edited your code to reflect my answer, there were two problems with your code that I saw.
Firstly, you need to use a colon in your command text to tell Oracle that clobparam is a bind variable, not a column name:
cmd.CommandText = "UPDATE table1 SET HTML_BODY = :clobparam";
Secondly, you were not setting the database connection anywhere on the command. Which connection should the command be using? In your situation you have only one connection but more generally it may be possible to have more than one connection open. Add the line
cmd.Connection = connection;
or alternatively create the command using
OracleCommand cmd = connection.CreateCommand();
Of course, it would be nice if Oracle.DataAccess returned an error message that gave you the slightest hint that this was what you were doing wrong.
Anyway, now that you've edited your question to include the critical detail ORA-02063: preceding line from ((servername)), which tells us that you are using a database link, all I can really do is echo what I wrote in the comment: connect direct to the remote database to transfer LOB data, don't use a database link.

Doesn't save added value into database

In Visual Studio (2013) I have added service-based database (Database1.mdf) in my project. I have added in it a table, and via Show Data Table added two rows. Reading data from database works as required. But there is a problem with add value to database. If I while the program is running add value to database and then press "Reading data" it's ok, the data is reading. But If I while the program is still running go to "Show Data Table" and press button "update", I get the error: "This database cannot be imported. It is either an unsupported SQL Server verison or an unsopported database compatibility".
If I press button "update" in "SQL Server Object Explorer" and then go to "Show Data Table" and press button "update", the data is updates, but no added data. Also, after the completion of the program there isn't the added data.
Why?
I have tried to change the properties "Copy To Output Directory" from "Copy always" to "Do not Copy" or "Copy if newer". But it didn't help me. Please help me
Read data:
string strConnectionString = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True";
using (SqlConnection con = new SqlConnection(strConnectionString))
{
try
{
SqlCommand command = new SqlCommand("SELECT [Login] FROM [UsersTable];", con);
con.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
label1.Text = "Last value: " + reader.GetString(0);
}
}
}
catch (SqlException ex)
{
}
Add data:
string strConnectionString = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True";
using (SqlConnection con2 = new SqlConnection(strConnectionString))
{
using (SqlCommand command2 = new SqlCommand())
{
command2.Connection = con2;
command2.CommandType = CommandType.Text;
command2.CommandText = "INSERT INTO [UsersTable] ([Login], [Password]) VALUES (#Login, #Password)";
command2.Parameters.AddWithValue("#Login", textLogin.Text);
command2.Parameters.AddWithValue("#Password", textPassword.Text);
try
{
con2.Open();
command2.ExecuteNonQuery();
}
catch (SqlException)
{
// error here
}
finally
{
con2.Close();
}
}
}
Update
Perhaps the example isn't clear enough for you.
private void SubmitNote(string message)
{
// Ensure parameter isn't null.
if(string.IsNullOrEmpty(message))
return;
// Our Insert Query:
string insert = #"INSERT INTO [Notes] ([Username], [Date], [Message])
VALUES (#Username, #Date, #Message);";
// Define our Connection & Command:
using(SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["db"].ConnectionString))
using(SqlCommand command = new SqlCommand(insert, connection))
{
// Open Connection
connection.Open();
// Define our Command (AddWithValue / Add Approach)
command.Parameters.Add("#Username", SqlDbType.VarChar, 50).Values = User.Identity.Name;
command.Parameters.AddWithValue("#Date", DateTime.Now);
command.Parameters.Add("#Message", SqlDbType.VarChar).Value = message;
// Execute Query:
command.ExecuteNonQuery();
}
}
So anytime I'd like to insert a message to the database I simply call:
SubmitNote("What is love, baby don't hurt me.");
That would execute without any issues, assuming the parameter and connection are valid. You could write an exception helper, but that is above and beyond your issue. One of the problems your potentially having is:
Parameter may be Null
An issue within your Command Text
Potential issue with your Connection String.
Based on the issue you mentioned, a value is Null which means it doesn't contain a valid value. For instance if you do:
String message = String.Empty;
SubmitNote(message);
That would fail, as message doesn't have a value. Hopefully this helps.

Inserting data into sql server fails with no reason

I'm quite used to using c# with SQL server. I have no idea why a simple statement would fail to insert data. My code is as follows:
query = "INSERT INTO MCDPhoneNumber ([MCDID],[PhoneNumber])" +
"VALUES("+maxid+", '"+tel+"')";
SqlConnection conn = new SqlConnection("Data Source=source; ...");
SqlCommand newCommand = new SqlCommand(query, conn);
int success= myCommand.ExecuteNonQuery();
if (success!= 1)
{
MessageBox.Show("It didn't insert anything:" + query);
}
First of all let me tell that I know that I should use parameters for data and I initially did, but when it failed I tried a simple query and it still fails. For addition I can tell that I have a similar insert just before that one in another table and it works. What's funnier is that when I copy paste query to SQL Server Management Studio it works. It also doesn't report any error in process.
====================== Edit ===============================
If you wish to use old command object (i.e. myCommand) then use following code instead of creating a new command(newCommand)
myCommand.CommandText = query;
myCommand.CommandType = System.Data.CommandType.Text;
And then execute it
you are binding query with newCommand and executing myCommand.
====================== Edit ===============================
SqlCommand newCommand = new SqlCommand(query, conn);
here you have defined newCommand for SQLCOMMAND object
int success= myCommand.ExecuteNonQuery();
and you are accessing it as myCommand
And moreover i think you are not opening connection
First of all, you define your command as newCommand but you executing your myCommand.
You should always use parameterized queries for your sql queries. This kind of string concatenations are open for SQL Injection attacks.
query = "INSERT INTO MCDPhoneNumber (MCDID, PhoneNumber) VALUES(#maxid, #tel)";
using(SqlConnection conn = new SqlConnection("Data Source=source; Initial Catalog=base; Integrated Security = true"))
{
SqlCommand newCommand = new SqlCommand(query, conn);
conn.Open();
newCommand.Parameters.AddWithValue("#maxid", maxid);
newCommand.Parameters.AddWithValue("#tel", tel);
int success= newCommand.ExecuteNonQuery();
if (success != 1)
{
MessageBox.Show("It didn't insert shit:" + query);
}
}
And please be more polite about your error messages :)

Categories