How to insert to service based database? - c#

I read lots of topics and tried many solutions, but it is not working for me, to insert my data to the database.
public static void Feltoltes(string szo_var, string szotagolva_var)
{
string query = "";
using (var conn = new SqlConnection(connectionString))
{
conn.Open();
using (var command = new SqlCommand(query, conn))
{
command.Parameters.Clear();
command.CommandText = "INSERT INTO Szavak (Szo,Szotagolva) VALUES ('#szo','#szotagolva')";
command.Parameters.AddWithValue("#szo", szo_var);
command.Parameters.AddWithValue("#szotagolva", szotagolva_var);
System.Windows.Forms.MessageBox.Show(command.CommandText);
command.ExecuteNonQuery();
}
conn.Close();
}
}
This is my code. My connection string is the right one. If I insert to the database manually, than I can make SELECTs etc. Only the Insert is not working properly. It don't get any exception, looks like everything works, but nothing changes.

Every thing looks OK except for the insert command text.
Try the following:
command.CommandText = "INSERT INTO Szavak (Szo,Szotagolva) VALUES (#szo,#szotagolva)";
If you use single quates (') inside a SQL command text it will treat what is inside as a literal. And hence it cancels out your parameter designation #

Related

How to override "duplicate entry warning" when run an append query (Access db, from c# asp.net)?

I have a query in the access database that appends email addresses from one table to another. In the source table there may be many duplicated emails. In the target table the email field is unique. Before running the query, there may already in the target table emails that are in the source table.
When running the query manually, I get a message about duplicates and I have to click on Yes to run the query anyway.
But when I try to run the query from the asp.net, c#, I get an exception and nothing is done.
How can I override the exception? I mean, how can I "tell" the system to assume I clicked on Yes after the warning?
Here is my code:
public static void RunQuery(string db, string command)
{
OleDbConnection conn = getConn(db); //set the value for conn
try
{
if (conn != null) conn.Close();
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = command; // query name
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception e)
{
log.Error(e);
throw;
}
finally
{
if (conn != null)
conn.Close();
}
}
Thanks
It has never been clear when/how the error msg of duplicates will trigger.
I find that this (in most cases) will run the append query, and errors are ignored.
This:
// run append query
using (OleDbConnection conn =
new OleDbConnection(Properties.Settings.Default.AccessDB))
{
using (OleDbCommand cmdSQL =
new OleDbCommand("AddToHotelss", conn))
{
conn.Open();
cmdSQL.CommandType = CommandType.StoredProcedure;
cmdSQL.ExecuteNonQuery();
}
}
Now, the above runs this saved query in Access:
INSERT INTO tblHotels2 ( FirstName, LastName, HotelName, EmailName )
SELECT tblHotels.FirstName, tblHotels.LastName, tblHotels.HotelName,
tblHotels.EmailName
FROM tblHotels
WHERE (tblHotels.City = "Edmonton");
And I have a unique index on EmailName - and the above works.
So, give the "setting" of CommandType = StoredProcedure.
The above SHOULD work.
If it does not?
Then you have to consider introduction of the office.interop ACE data engine. (I don't think that's a good idea).
Or, if above idea does not work?
You have to modify your query to prevent duplicates in the first place..
The query then becomes this:
INSERT INTO tblHotels2 ( FirstName, LastName, HotelName, EmailName )
SELECT tblHotels.FirstName, tblHotels.LastName, tblHotels.HotelName,
tblHotels.EmailName
FROM tblHotels
WHERE (tblHotels.City="Edmonton")
AND
(tblHotels.EmailName NOT IN (SELECT EmailName from tblHotels2.EmailName));
So, as suggested, you re-write the query to never allow duplicates.
I would however give the commandText setting (StoredProcedure) as per above - since in the past I had that work for me. (the duplicates message did not trigger, or stop the append).

C# MS SQL Update statement not updating database

I have a local MS SQL Database, and I want to update one of it's bit field.
I have the following code:
static void UpgradeVevo(string nev)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("UPDATE Vevok SET Torzsvendeg=True Where Nev=" + nev, connection);
command.ExecuteNonQuery();
}
Console.WriteLine(nev+" mostmár törzsvendég");
}
Torzsvendeg is a bit datatype(I have tried to set its value to 1 too), and Nev is varchar.
The connectionstring should be fine, since I have tried Select in another method and it works fine. The above code throws no exceptions, but the table does not get updated.
I have tried to find an answer for quite some time, with no success :/. Thank you for your help in advance!
True should be in a single quote since it's a string literal like
UPDATE Vevok SET Torzsvendeg='True'
Well brother, you are messed up with quotes. Your query should look like
"UPDATE Vevok SET Torzsvendeg = 1 Where Nev = '" + nev + "'"
Again, use parametarized query and not this concatenated one to avoid SQL Injection
If the column is a boolean (bit in sql server) then you will have to write
Torzsvendeg=1
instead of
Torzsvendeg='True'
or
Torzsvendeg=True
Edit:
Please try this:
static void UpgradeVevo(string nev)
{
var connection = new SqlConnection(connectionString))
connection.Open(); // try doing this without a using
SqlCommand command = new SqlCommand("UPDATE Vevok SET Torzsvendeg=#enabled Where Nev=#nev", connection);
command.Parameters.AddWithValue(#"enabled", 1);
command.Parameters.AddWithValue(#"nev", "vevo123");
command.ExecuteNonQuery();
command.Parameters.Clear(); // always clear after executed
// close connection when you shut down your application
connection.Close();
connection.Dispose();
Console.WriteLine(nev+" mostmár törzsvendég");
}

How to use a parameter for a SQL Server query that is part of the query itself using SqlDataReader in C# asp.net

Background
I am trying to retrieve the count of occurrences of a user in the database at the same time as returning the data set. How do I accomplish this? My code is below of what I have so far.
If I hard code the username, for the row, I get the expected output. However, I am having problems declaring a parameterized query variable with this code. Any help would be appreciated. I have been working on this for quite some time now.
protected void Page_Load(object sender, EventArgs e)
{
string ConnStr = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
using (SqlConnection conn = new SqlConnection(ConnStr))
{
string Command = "SELECT TOP 3 *, Counter = (select Count(User) from Projects where [User]='jmoore00' AND Account = 'ACTIVE') FROM Projects";
using (SqlCommand comm = new SqlCommand(Command, conn))
{
conn.Open();
SqlDataReader rdr = comm.ExecuteReader();
ListView.DataSource = rdr;
ListView.DataBind();
rdr.Close();
}
}
}
Above, 'jmoore00' should be scalar variable #User but how do I appropriately declare and use the variable with value equaling rdr["user"] if I am using the code the way it is?
I think you should use Stored Procedure in you sql.as a specific user try to retrieve its data, do add number of this occurrence to a field in your sql.
each user has a unique field which can be in access with their users or userID.
but i think it will increase transaction time .
hope it would be helpful

C#: Input data from string array into MS Access DB Table

I've searched as much as I can and can't find anything to help me. So what I have is a script that reads/splits and stores data from a .txt file into some arrays. (The one listed here is Vndnbr). What I'm having trouble with is how to go about inputting each entry in the array as an entry under a column in a MS Access table? This is what I have so far:
public void AddToDatabase()
{
OleDbCommand command;
OleDbConnection connection =
new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=filepath");
foreach (string x in Vndnbr)
{
cmdstringVND[k] = "insert into Table1 (Vndnbr) Values (x)";
k++;
command = OleDbCommand(cmdstringVND[k],connection);
}
command.Parameters.AddWithValue("?", ReadFromFile("filepath"));
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
I'm not familiar with the Access library or what should be inserted in the first parameter of AddwithValue as I just copy pasted these lines after doing some research.
If someone could help me with how to add all the data from an array into a table it would be greatly appreciated, thanks.
There are many errors in your code
In your loop you don't use a parameter to store the value to be
inserted
You never creare the command. (Use new)
You try to execute only the last command because the ExecuteNonQuery is outside the loop
public void AddToDatabase()
{
string cmdText = "insert into Table1 (Vndnbr) Values (?)";
using(OleDbConnection connection = new OleDbConnection(.....))
using(OleDbCommand command = new OleDbCommand(cmdText, connection))
{
connection.Open();
command.Parameters.AddWithValue("#p1", "");
foreach (string x in Vndnbr)
{
command.Parameters["#p1"].Value = x;
command.ExecuteNonQuery();
}
}
}
I have changed you code to include the using statement to correctly close and dispose the connection and the command, then I have initialized the command outside the loop, passed a common string with as a parameter placeholder and initialized this parameter with a dummy value.
Inside the loop I have replaced the previous parameter value with the actual value obtained by your Vndnbr list and executed the command.
You'll want to change your SQL to this:
"insert into Table1 (Vndnbr) Values (#x)";
and then the AddWithValue is like this:
command.Parameters.AddWithValue("#x", ReadFromFile("filepath"));
All you're doing is saying, for this parameter name, I want this value assigned.

How to update a large table using ADO.NET

Ok, so here's the problem I have to solve. I need to write a method in C# that will modify a table in SQL Server 2008. The table could potentially contain millions of records. The modifications include altering the table by adding a new column and then calculating and setting the value of the new field for every row in the table.
Adding the column is not a problem. It's setting the values efficiently that is the issue. I don't want to read in the whole table into a DataTable and then update and commit for obvious reasons. I'm thinking that I would like to use a cursor to iterate over the rows in the table and update them one by one. I haven't done a whole lot of ADO.NET development, but it is my understanding that only read-only server side (firehose) cursors are supported.
So what is the correct way to go about doing something like this (preferably with some sample code in C#)? Stored procedures or other such modifications to the DB are not allowed.
jpgoody,
Here is an example to chew on using the NerdDinner database and some SQLConnection, SQLCommand, and SQLDataReader objects. It adds one day to each of the Event Dates in the Dinners table.
using System;
using System.Data.SqlClient;
namespace NerdDinner
{
public class Class1
{
public void Execute()
{
SqlConnection readerConnection = new SqlConnection(Properties.Settings.Default.ConnectionString);
readerConnection.Open();
SqlCommand cmd = new SqlCommand("SELECT DinnerID, EventDate FROM Dinners", readerConnection);
SqlDataReader reader = cmd.ExecuteReader();
SqlConnection writerConnection = new SqlConnection(Properties.Settings.Default.ConnectionString);
writerConnection.Open();
SqlCommand writerCommand = new SqlCommand("", writerConnection);
while (reader.Read())
{
int DinnerID = reader.GetInt32(0);
DateTime EventDate = reader.GetDateTime(1);
writerCommand.CommandText = "UPDATE Dinners SET EventDate = '" + EventDate.AddDays(1).ToString() + "' WHERE DinnerID = " + DinnerID.ToString();
writerCommand.ExecuteNonQuery();
}
}
}
}
Your problem looks like something that you should be solving using T-SQL and not C#, unless there is some business rule that you are picking up dynamically and calculating the column values T-SQL should be the way to go. Just write a stored procedure or just open up Management studio and write the code to make your changes.
If this does not help then please elaborate on what exactly you want to do to the table, then we can help you figure out if this can be done via T-SQL or not.
[EDIT] you can do something like this
string sql = " USE " + paramDbName;
sql+= " ALTER TABLE XYZ ADD COLUMN " + param1 + " datatype etc, then put semicolon to separate the commands as well"
sql+= " UPDATE XYZ SET Columnx = " + some logic here
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
get this executed on the required instance of Sql Server 2008.
If you have too many lines of text then use StringBuilder.
Here's a suggestion:
You can read data using a DataReader , create a update command for current row and add it to a list of commands.Then run update commands in a transaction.
something like this:
var commands=new List<SqlCommand>();
while(dr.Read())
{
var cmd=new SqlCommand();
cmd.CommandText="Add your command text here";
commands.Add(cmd);
}
using(var cnn=new SqlConnection("Connection String"))
{
IDbTransaction transaction;
try
{
cnn.Open();
transaction=cnn.BeginTransaction();
foreach(var cmd in commands)
{
cmd.Transaction=transaction;
cmd.ExecuteNonQuery();
cmd.Dispose();
}
transaction.Commit();
}
catch(SqlException)
{
if(transaction!=null)
transaction.Rollback();
throw;
}
}

Categories