After setting up my SqlDataSource on another page to display the values, they come up as 2 blanks for the 2 times I entered test values on the comments page.
I think I'm missing something in getting them into the table in the SQL Server database value?
I'm not sure what information is needed here, so please inform me.
Thanks in advance
EDIT #1 for user request for CODE
protected void btnSend_Click(object sender, EventArgs e)
{
Page.Validate("vld2");
SendMail();
lblMsgSend.Visible = true;
//SQL Server Database
SqlConnection conn; //manages connection to database
SqlCommand cmd; //manages the SQL statements
string strInsert; //SQL INSERT Statement
try
{
//create a connection object
conn = new SqlConnection("Data Source=localhost\\sqlexpress;" +
"Initial Catalog=RionServer;" +
"Integrated Security=True;");
//Build the SQL INSERT Document
strInsert = "INSERT INTO CommentsAdmin (Name,Phone,Email,Comments)"
+ "VALUES(#Name,#Phone,#Email,#Comments);";
//associate the INSERT statement with the connection
cmd = new SqlCommand(strInsert, conn);
//TELL the SqlCommand WHERE to get the data from
cmd.Parameters.AddWithValue("Name", txtName.Text);
cmd.Parameters.AddWithValue("Phone", txtPhone.Text);
cmd.Parameters.AddWithValue("Email", txtEmail.Text);
cmd.Parameters.AddWithValue("Comments", txtComment.Text);
//open the connection
cmd.Connection.Open();
//run the SQL statement
cmd.ExecuteNonQuery();
//close connection
cmd.Connection.Close();
//display status message on the webpage
lblMsgSend.Text = "Thank you for the comment! Please hit the 'Return to Main Page' to return to the Main Page!";
}
catch (Exception ex)
{
lblMsgSend.Text = ex.Message;
}
txtPhone.Text = "";
txtEmail.Text = "";
txtName.Text = "";
txtComment.Text = "";
}
EDIT #2
The values seems to be empty for the Name, Phone, Email, and Comments in the database and when I test the query, so I think it's registering the entries, just not taking the values into the SQL?
EDIT #3
Due to a suggestion by coder and rs, I've done what they've said. And now I get this error.
"String or binary data would be truncated. The statement has been terminated."
The code has been updated as well.
EDIT #4
This question is a follow up for SQL Server Error, 'Keyword not supported 'datasource'.
Remove all the "" similar to this txtPhone.Text = ""; before entering values to SQL as Server you're entering null values to that. So even if you give some values to the textbox it takes predefined NULL values and it dosen't enter either of them.
Related
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.
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.
I'm building a user registration page that save user's info into a local database. However I get a SqlException error. Does anyone know what I'm doing wrong here? I'm developing the program in ASP.net and using the local database server.
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegisterConnectionString"].ConnectionString);
conn.Open();
string checkUser = "select count(*) from Table where userName = '" + txtUN.Text + "'";
SqlCommand comm = new SqlCommand(checkUser, conn);
int temp = Convert.ToInt32(comm.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("user already exist");
}
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegisterConnectionString"].ConnectionString);
conn.Open();
string insertQuery = "insert into Table(UserName, name, Address, e-Mail, IC, phone, password) values(#Uname, #name, #add, #mail, #ic, #phone, #pswrd) ";
SqlCommand comm = new SqlCommand(insertQuery, conn);
comm.Parameters.AddWithValue("#Uname", txtUN.Text);
comm.Parameters.AddWithValue("#name", txtName.Text);
comm.Parameters.AddWithValue("#add", txtAdd.Text);
comm.Parameters.AddWithValue("#mail", txtEmail.Text);
comm.Parameters.AddWithValue("#ic", txtIC.Text);
comm.Parameters.AddWithValue("#phone", txtPhone.Text);
comm.Parameters.AddWithValue("#pswrd", txtPsswrd.Text);
comm.ExecuteNonQuery();
Response.Redirect("Default.aspx");
Response.Write("registration was succesful");
conn.Close();
}
catch(Exception ex)
{
Response.Write("error"+ex.ToString());
}
}
You don't give the details of the exception, (ie: exception.Message and exception.InnerException.Message) but from your code I think you have the classical "Syntax Error Near ...."
This is caused by the presence of a reserved keyword in your query text. This reserved keyword is TABLE. You could fix it enclosing the word in square brackets (or better change the name of the table to somenthing more meaningful)
string checkUser = "select count(*) from [Table] where userName = ...";
A part from this, remember to use always parameterized queries also for simple tasks as looking for logins. Last but not least, storing password in clear text inside the database is a big NO-NO from a security standpoint. Everyone, having access to your database using some kind of administrative tool, could look at the passwords of your users, someone could intercept the network traffic between user pc and database server and see the credentials sent by your application. So, please, search for password hashing on this site to find a more secure approach to this problem
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.
I have read TONS of tutorials, articles and whatever regarding my issue and honestly, due to my lack of experience I can't twist my fingers around this one so I hope some of you guys can help me out :)
I am working on a project (simply to learn how to program so it's probably very basic), but I have this "News" page where I can update and delete data using a GridView.
Now I would like to INSERT something into my database using 3 textboxes and 1 submit button.
I have 3 rows that has to be inserted:
Headline
Date
Content/the news itself.
Which are stored under NyhedTB from the connectionstring: BoligStjernenConnectionString
My query looks like this:
INSERT INTO [NyhedTB] ([NyhedDato], [NyhedTitel], [NyhedTekst])
VALUES (#NyhedDato, #NyhedTitel, #NyhedTekst)
I read on the internet that this code should do the magic for me (I will have to insert my own values ofc.):
static void Insert()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=sa123";
using (SqlConnection conn =
new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("INSERT INTO EmployeeDetails VALUES(" +
"#Id, #Name, #Address)", conn))
{
cmd.Parameters.AddWithValue("#Id", 1);
cmd.Parameters.AddWithValue("#Name", "Amal Hashim");
cmd.Parameters.AddWithValue("#Address", "Bangalore");
int rows = cmd.ExecuteNonQuery();
//rows number of record got inserted
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
I looked at this code and thought it should be easy enough but really, I can't figure it out.
Here is some advice to get you going, learning programming is a lot of
trial and error.
Start off basic, litrally put three textboxes on a form/page and a
button.
Double click the button to go the code-behind and view the buttons
click event.
Paste in the body of code included with your question (everything in the try-catch).
Put a break-point on the Public Void Button_Click line of code and press F11 to
step through the code.
"one thing is having the code-behind working but how to make the buttons and textboxes working is still a misery"*
Put the textbox as the value rather than your hardcoded values:
cmd.Parameters.AddWithValue("#Address", textBox1.Text);
You also should not insert the Id value, instead modify the EmployeeDetails table and set the ID column to in the properties set Identity Specification (IS Identity) = True. Then right click the ID column and set Primary Key.
Post any error messages you encounter here and when you do get get it working, an additional exercise (that will be very valuable for you) would use a database stored procedure rather than ad-hoc SQL, to safe-guard against sql-injection attacks.
I'm assuming you have SQL Server installed and have a 'employee' database with a table called EmployeeDetails.
protected void GvManualShows_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//label lbl = (label)e.Row.FindControl("lblHidden");
if (e.Row.Cells[14].Text == "Y")
{
// CheckBox cb = (CheckBox)e.Row.FindControl("chk");
CheckBox chk = (CheckBox)e.Row.Cells[0].FindControl("chkBox");
chk.Checked = true;
}
}
}
It's fairly simple. You just have to modify the connection string, the query and its parameters:
private void button1_Click(object sender, EventArgs e)
{
try
{
string connectionString =
"server=SQLServer;" + // SQLServer is your SQL server machine
"initial catalog=employee;" + // employee is your database
"user id=sa;" + // sa is the login to connect the database
"password=sa123"; // sa123 is the password of the login
using (SqlConnection conn =
new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(
"INSERT INTO [NyhedTB] ([NyhedDato], [NyhedTitel], [NyhedTekst]) " +
"VALUES (#NyhedDato, #NyhedTitel, #NyhedTekst)", conn))
{
cmd.Parameters.AddWithValue("#NyhedDato", textBoxDate.Text);
cmd.Parameters.AddWithValue("#NyhedTitel", textBoxTitle.Text);
cmd.Parameters.AddWithValue("#NyhedTekst", textBoxBody.Text);
int rows = cmd.ExecuteNonQuery(); // Inserted rows number
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
I made changed example code with your requirements and added comments, hope it would be a bit clearer for you to understand whats going on:
static void Insert()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=MyDatabaseName;" + //here you write database name where your NyhedTB table is
"user id=sa;" + //user name to connect to database
"password=sa123"; //password
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("INSERT INTO NyhedTB (NyhedDato, NyhedTitel, NyhedTekst) VALUES (#NyhedDato, #NyhedTitel, #NyhedTekst)", conn))
{
//all "things" in your sql command what beggins with #
//means that it is parameter and you need to pass values for these parameters:
//For #NyhedDato parameter you set text from your textbox
cmd.Parameters.AddWithValue("#NyhedDato", txtDate.Text);
//For #NyhedTitel parameter you set text from title textbox
cmd.Parameters.AddWithValue("#NyhedTitel", txtTitle.Text);
//For #NyhedTekst parameter you set text from content textbox
cmd.Parameters.AddWithValue("#NyhedTekst", txtContent.Text);
//Execute insert command and get how many records was efected, in this case it should be rows = 1 because you inserting just one record
int rows = cmd.ExecuteNonQuery();
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
P.s. code not tested. And when you say
I have 3 rows that has to be inserted:
Headline
Date
Content/the news itself.
actually you mean you want to insert record with fields