I was trying to store the url on button click using the following code.There were no error but the required url is not sroeing in my column field (i used ntext data tpe for this).Please help me if there was some mistake in my code
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void Storetxt(String txt)
{
//connection to the database
string connection = "Data Source=.\\sqlexpress2005;Initial Catalog=PtsKuratlas;Integrated Security=True";
SqlConnection conn = new SqlConnection(connection);
//dataset object to store and manipulating data
DataSet myDataSet = new DataSet();
//data adapters to execute SQL
SqlDataAdapter myDataAdapter = new SqlDataAdapter("SELECT * FROM gti_analytics", conn);
myDataAdapter.Fill(myDataSet, "gti_analytics");
myDataAdapter.InsertCommand = new SqlCommand("INSERT INTO gti_analytics [links] VALUES [txt]");
}
protected void Button1_Click(object sender, EventArgs e)
{
String text = "http://google.com";
Storetxt(text);
}
}
The problem is that you're not actually executing the command against the database. You're defining the InsertCommand to use, but it's not being executed.
Based on that code, I don't see that you need to use a DataAdapter/DataSet anyway, just use an SqlCommand to do the insert, which is more lightweight. Something like this:
public void Storetxt(String txt)
{
//connection to the database
string connection = "Data Source=.\\sqlexpress2005;Initial Catalog=PtsKuratlas;Integrated Security=True";
SqlConnection conn = null;
SqlCommand cmd = null;
try
{
conn = new SqlConnection(connection);
cmd = new SqlCommand("INSERT INTO gti_analytics (Links) VALUES (#Link)", conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Link", txt);
conn.Open();
cmd.ExecuteNonQuery();
}
catch{//handle exceptions}
finally
{
if (cmd != null) cmd.Dispose();
if (conn != null)
{
if (conn.State == ConnectionState.Open) conn.Close();
conn.Dispose();
}
}
}
I'd also recommend not using ntext for this in your db. If you really need unicode support, use nvarchar which can go up to 4000 chars pre-sql 2005, or nvarchar(max) which can store as much as ntext from SQL 2005 onwards. If you don't need unicode support, use varchar instead (8000 chars pre-sql 2005, VARCHAR(MAX) from SQL 2005 onwards allows same as text)
shouldn't you be calling myDataAdapter.Update() at the end of the Storetxt method?
oh and i think using ntext for this is overkill.
Your txt method argument is not actually used anywhere in your method which is one reason why it's not being stored in the db.
You don't need a SqlDataAdapter or a DataSet for this operation, as AdaTheDev said. Follow the sample code, although it needs quite a bit of cleaning up.
Also, there's a protocol limit on the number of characters/bytes in the URL, nvarchar should have enough maximum capacity, so you should need neither nvarchar(max) nor (pre-SQL Server 2005) ntext.
Related
I'm attempting to connect to a database and insert data into the pre-existing table. I'm able to connect to the database it seems but am having trouble getting the data to insert into the table. How do I insert
data into a database in visual studio?
I've already learned how to pass parameters and attempted that, but when I run the program I still receive exceptions. I've attached a screenshot of the error when I try and add a new record. I've looked up multiple different syntaxes for the insert statement, but not sure what I am doing wrong. Below I've included three screenshots one is the form itself, the error I receive, and at the bottom the table structure.
Insert Exception
Form
private void btnAccept_Click(object sender, EventArgs e)
{
if (IsValidData())
{
if (addProduct)
{
product = new Product();
this.PutProductData(product);
try
{
SqlConnection sqlConn = new SqlConnection("Data Source= (LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\MMABooks.mdf;Integrated Security=True");
SqlCommand sqlComm = new SqlCommand();
sqlComm = sqlConn.CreateCommand();
sqlComm.CommandText = #"INSERT INTO Products (paramColum) VALUES
(#ProductCode, #Description,
#UnitPrice, #OnHandQuantity)";
sqlComm.Parameters.Add("#ProductCode", SqlDbType.VarChar);
sqlComm.Parameters.Add("#Description", SqlDbType.VarChar);
sqlComm.Parameters.Add("#UnitPrice", SqlDbType.VarChar);
sqlComm.Parameters.Add("#OnHandQuantity", SqlDbType.VarChar);
sqlConn.Open();
sqlComm.ExecuteNonQuery();
sqlConn.Close();
// Add code here to call the AddProduct method of the ProductDB class.
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, ex.GetType().ToString());
}
}
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
frmAddModifyProduct addProductForm = new
frmAddModifyProduct();
addProductForm.addProduct = true;
DialogResult result = addProductForm.ShowDialog();
if (result == DialogResult.OK)
{
product = addProductForm.product;
txtCode.Text = product.Code;
this.DisplayProduct();
}
}
It should enter a record into the Products table. If I get it down for the insert statement, I'll figure out the retrieve, update, and delete.
TableStructure
You need to add the parameter values, something like:
command.Parameters.Add("#LastName", SqlDbType.VarChar, 30).Value = "Smith";
command.Parameters.Add("#GenderCode", SqlDbType.Char, 1).Value = "M";.
Original answer below, but as pointed in comments below, please avoid it, reasons
cmd.Parameters.AddWithValue("#ProductCode", product.Code);
cmd.Parameters.AddWithValue("#Description", product.Description);
In the current code you have just setup the parameters but not passed the value.
EDIT: Based on #MaxSzczurek comments above
Your INSERT INTO columns don't match your VALUES clause.
INSERT INTO Products (paramColumn) should be changed to:
INSERT INTO Products(ProductCode, Description, UnitPrice, OnHandQuantity)
I am trying to insert values into my SQL database, the query works on the SQL side but when it comes to implement it from C# ASP.NET, it will not insert anything into the SQL database. The code is as follows:
public partial class About : Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into sanctuary(SName) values('test')", con);
cmd = new SqlCommand("insert into species(Name) values('test1')", con);
cmd = new SqlCommand("insert into breed(SpeciesID, BreedName, FoodCost, HousingCost) SELECT SpeciesID, ('breed'), ('12'), ('21') FROM species", con);
cmd.ExecuteNonQuery();
con.Close();
}
}
}
Your help will be much appreciated!
If you want to execute three commands together you merge the sql of the three commands in a single string separating them with a semicolon (See Batch of Sql Commands)
string cmdText = #"insert into sanctuary(SName) values('test');
insert into species(Name) values('test1');
insert into breed(SpeciesID, BreedName, FoodCost, HousingCost)
SELECT SpeciesID, ('breed'), ('12'), ('21') FROM species";
SqlCommand cmd = new SqlCommand(cmdText, con);
cmd.ExecuteNonQuery();
The first problem in your code is that you need to execute each single command and not just the last one. Finally, if you don't see even the insert for the last command could be because your table species is empty and thus the final command has nothing to insert.
Last note, the point underlined by Zohar Peled about NOT keeping a global connection object around, is very important, follow the advice.
You only execute the last command, so there is nothing in species. Since there is nothing in species, the select returns no results so nothing gets inserted into breed.
Also, keeping an SqlConnection object on the page level is not a good idea. SQL connections should be opened right before executing queries and disposed immediately after.
A better code would look like this:
using(var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using(var com = new SqlCommand("insert into sanctuary(SName) values('test');insert into species(Name) values('test1');insert into breed(SpeciesID, BreedName, FoodCost, HousingCost) SELECT SpeciesID, ('breed'), ('12'), ('21') FROM species", con)
{
con.Open();
com.ExecuteNonQuery();
}
}
You can, of course, execute each SQL statement separately (though in this case it's not the best course of action since it means 3 round trips to the database instead of just one):
using(var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using(var com = new SqlCommand("insert into sanctuary(SName) values('test');", con)
{
con.Open();
com.ExecuteNonQuery();
com.CommandText = "insert into species(Name) values('test1');";
com.ExecuteNonQuery();
com.CommandText = "insert into breed(SpeciesID, BreedName, FoodCost, HousingCost) SELECT SpeciesID, ('breed'), ('12'), ('21') FROM species;";
com.ExecuteNonQuery();
}
}
Every time I try to run my code, I get this exception:
An unhandled exception of type 'System.Data.SqlClient.SqlException'
occurred in System.Data.dll
Additional information: Incorrect syntax near ')'.
Tried multiple workarounds, but I never get past the ExectueNonQuery line. Can someone tell me what's wrong with it?
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=CHARLIE-PC\MSSQLSERVER1;Initial Catalog=Tema;Integrated Security=True;");
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Fisier (idFisier, Nume, idFolder) VALUES ('"+idFis.Text+ "','"+ numeFis.Text + "','" +idFoldFis.Text +"',)", con);
cmd.ExecuteNonQuery();
con.Close();
}
While the other questions state the root problem, your trailing comma, you really must do better about your queries. Do not glue your query together like that, use parameters instead. If you do not you are opening yourself to huge security problems. Also you really must put the connection in a using statement so when a error does happen the connection will still be closed.
private void button1_Click(object sender, EventArgs e)
{
using(SqlConnection con = new SqlConnection(#"Data Source=CHARLIE-PC\MSSQLSERVER1;Initial Catalog=Tema;Integrated Security=True;"))
{
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Fisier (idFisier, Nume, idFolder) VALUES (#idFis,#numeFis,#idFoldFis)",con);
cmd.Parameters.Add("#idFis", SqlDbType.NVarChar, -1).Value = idFis.Text;
cmd.Parameters.Add("#numeFis", SqlDbType.NVarChar, -1).Value = numeFis.Text;
cmd.Parameters.Add("#idFoldFis", SqlDbType.NVarChar, -1).Value = idFoldFis.Text;
cmd.ExecuteNonQuery();
}
}
The comma is your problem, but I would recommend a few other changes at least before moving on:
Don't embed your connection strings into each db connection request. Use app.config/web.config or anything else :)
Ensure your connections are commands are properly disposed of
Parameterize any SQL queries to prevent injection attacks
Abstract database commands into separate business layer
1. Utilize an "app.config" for connection strings
There are many docs out there on keeping a connection string secure, but at a minimum, don't embed straight into each of your connection code.
Add an "app.config" to your client project (or utilize the web.config of web projects). At a minimum, this looks like this:
<configuration>
<appSettings>
<add key="db" value="Data Source=CHARLIE-PC\MSSQLSERVER1;Initial Catalog=Tema;Integrated Security=True;" />
</appSettings>
</configuration>
Then add a reference to "System.Configuration" to your project, and you can reference it like this in your code:
var con = new SqlConnection(ConfigurationManager.AppSettings["db"]);
2. Ensure your connections ard commands are properly disposed
Wrap connections and commands in using. Here is an example:
using (var con = new SqlConnection(ConfigurationManager.AppSettings["db"]))
{
con.Open();
var sql = "/* My command here */";
using (var cmd = new SqlCommand(sql, con))
{
// SQL execution here
}
} // Closing is now handled for you (even if errors occur)
3. Parameterize any SQL queries to prevent injection attacks
Concatenating strings are very dangerous for SQL commands (just google "SQL Injection"). This is how to protect yourself.
using (var con = new SqlConnection(ConfigurationManager.AppSettings["db"]))
{
con.Open();
var sql = "INSERT INTO Fisier (idFisier, Nume, idFolder) VALUES (#idFisier, #nume, #idFolder)";
using (var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add("#idFisier", SqlDbType.VarChar).Value = idFis.Text;
cmd.Parameters.Add("#nume", SqlDbType.VarChar).Value = numeFis.Text;
cmd.Parameters.Add("#idFolder", SqlDbType.VarChar).Value = idFoldFis.Text;
cmd.ExecuteNonQuery();
}
} // Closing is now handled for you (even if errors occur)
4. Abstract database commands into separate business layer
It is usually best practice and will save you many headaches by writing separate classes (even class library) as your business layer that only contain your data commands. Then your UI would only handle calling the business layer methods.
If your database ever changes or you need to do similar functionality in other parts of your UI, it won't be very fun updating the same query all over your UI as opposed to just updating a single spot in your business layer.
Make SQL being readable and parametrized and you'll find the routine easy to implement:
// Extract a method (or even a class): do not mix UI and business logic/storage
// Just RDBMS logic: no UI controls or something at all
private static void CoreInsertFisier(string idFisier, nume, idFolder) {
// Do not hardcode the connection string, but read it (from settings)
// wrap IDisposable into using
using (SqlConnection con = new SqlConnection(ConnectionStringHere)) {
con.Open();
// Make sql readable (use verbatim strings #"...")
// Make sql parameterized
string sql =
#"INSERT INTO Fisier (
idFisier,
Nume,
idFolder)
VALUES (
#prm_idFisier,
#prm_Nume,
#prm_idFolder)";
// wrap IDisposable into using
using (SqlCommand cmd = new SqlCommand(sql, con)) {
// Parameters.Add(...) is a better choice, but you have to know fields' types
cmd.Parameters.AddWithValue("#prm_idFisier", idFisier);
cmd.Parameters.AddWithValue("#prm_Nume", nume);
cmd.Parameters.AddWithValue("#prm_idFolder", idFolder);
cmd.ExecuteNonQuery();
}
}
}
...
private void button1_Click(object sender, EventArgs e) {
// UI: just one call - please insert these three textbox into db
CoreInsertFisier(idFis.Text, numeFis.Text, idFoldFis.Text);
}
You have an extra trailing comma:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=CHARLIE-PC\MSSQLSERVER1;Initial Catalog=Tema;Integrated Security=True;");
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Fisier (idFisier, Nume, idFolder) VALUES ('"+idFis.Text+ "','"+ numeFis.Text + "','" +idFoldFis.Text +"')",con);
cmd.ExecuteNonQuery();
con.Close();
}
Anyway as others said, it is a very bad idea to concatenate your query that way, since it could lead you to have sql injection on your code.
Try removing the , before the closing )
SqlCommand cmd = new SqlCommand("INSERT INTO Fisier (idFisier, Nume, idFolder) VALUES ('"+idFis.Text+ "','"+ numeFis.Text + "','" +idFoldFis.Text +"')",con);
i want to delete data in my database and using this code but its now working
private static void DeletePreviousRecord()
{
string connectionString = "Data Source=ABDULLAH\\ABDULLAHZAFAR;Initial Catalog=FoodHunt;Integrated Security=True";
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("Delete From RestaurantsMenu", con))
{
try
{
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
var result = cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{ }
}
}
}
i tried this but this is not working, how can i do that, any suggestion?
Setting the CommandType to StoredProcedure when you clearly use a sql text directly cannot do any good at your code.
Remove that line because the default is CommandType.Text (and this is correct for your command)
But as stated in the comment above.
If you catch the exception, at least write in some log or display at
video what the error message is
If you don't add a WHERE clause at your sql statement, you delete
everything in the table (Probably you are lucky that this code has
not worked)
Looking at your comment below, if you want to delete every record (and reset the Identity column if any) a faster approach is
using (SqlCommand cmd = new SqlCommand("TRUNCATE TABLE RestaurantsMenu", con))
For a quick reading about the difference between TRUNCATE and DELETE look at this article
This is my code for insert into a table. It doesn't get any error, but it doesn't insert to the table. I tried by using stored_procedure too but it doesn't insert too. I can't find what I'm doing wrong.
private void btnSave_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = Properties.Settings.Default.bm_DatabaseConnectionString;
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
//cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "INSERT INTO [tbl_Buildings] (buildingName,buildingImage,buildingAddress,floorNo,apartsNo, buildingDesc) VALUES (#builName,#builImage,#builAddr,#floorNo,#apartsNo,#builDesc)";//"prc_AddNewBuilding";
cmd.Parameters.Add("#builName", txtBuildingName.Text);
cmd.Parameters.Add("#builAddr", txtAddress.Text);
cmd.Parameters.Add("#builImage", "Undefined");
cmd.Parameters.Add("#floorNo", (int)numFloorNo.Value);
cmd.Parameters.Add("#apartsNo", (int)numApartsNo.Value);
cmd.Parameters.Add("#builDesc", txtBuilDesc.Text);
try
{
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("New building has been added successfully");
this.Close();
}
catch (SqlException sqlex)
{
MessageBox.Show(sqlex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
I am using VS2012. What could I be doing wrong?
Try using:
Database.Command.Parameters.AddWithValue("#variableName", variable)
The only thing I could imagine why your values won't be inserted into your DB is a SQL Exception. Maybe you're missing some quotes?
Alternatiely use the complete "Add" Statement like this:
Database.Command.Parameters.Add(item, System.Data.SqlDbType.VarChar).Direction = ParameterDirection.Input
Item in this case is your variable containing the data you want to store
EDIT
My original answer assumed SQL Server was the database. As it turns out, the OP is using MS Access. Seems, based on other evidence, the file path for the .mdb file was the culprit, not the C# or SQL.
My original answer:
Using the connection string...
Server=myhost;Database=testdatatbase;Trusted_Connection=True;
the code you provided above works. I went to SQL Enterprise Manager, created a table named dbo.tbl_Buildings with the following attributes...
buildingName = nvarchar(50)
buildingImage = nvarchar(50)
buildingAddress = nvarchar(50)
floorNo = int
apartsNo = int
buildingDesc = nvarchar(50)
I then passed in dummy values, then ran the following query...
select * from testdatatbase.dbo.tbl_Buildings
and it shows the record....
-- seems to work for me...
(Maybe check your datatypes - make sure your table types match your types in the code)