C# to database (textboxes) - c#

I want to use my textboxes to send data to my database.
The problem is that he doesn't know loonberekening.tblWerknemer, I always get
incorrect syntax near 'tblWerknemer'
Here is a picture of my tables: http://gyazo.com/1a92845f51f56ef37e9ae3adf3f23a7c
string database = (#"Data Source=(LocalDB)\v11.0;AttachDbFilename=E:\gip_stap_2\loonberekening.mdf;Integrated Security=True;Connect Timeout=30");
string werknemergegevens = "insert into loonberekening.tblWerknemer (naam,voornaam) values ('"+txtNaam.Text+"','"+txtVoornaam.Text+"');";
SqlConnection cnnLoonberekening = new SqlConnection(database);
SqlCommand scmdLoon = new SqlCommand(werknemergegevens, cnnLoonberekening);
SqlDataReader check;
try{
cnnLoonberekening.Open();
check = scmdLoon.ExecuteReader();
MessageBox.Show("Opgeslagen");
while (check.Read())
{
}
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}

Try "insert into loonberekening.dbo.tblWerknemer"
also as an aside look into parameterisation of the values.

Either add ;InitialCatalog=loonberekening to the end of the connection string to specify the database or add a schema name to the query: loonberekening.dbo.tblWerknemer.
There will be nothing to read back from an insert as you appear to be attempting
You need to use an SQLCommand to prevent what will happen if you run your code with a ' anywhere in the textbox. (SQL Injection)

Try "insert into loonberekening.dbo.tblWerknemer"
or
only "insert into tblWerknemer"
then rest parts

Try rewrite the query as insert into dbo.tblWerknemer ..., because loonberekening is the database name and dbo.tblWerknemer is the actual table name
Also try to use parametrized query instead of directly passing values to prevent sql injection.
http://www.dreamincode.net/forums/topic/268104-parameterizing-your-sql-queries-the-right-way-to-query-a-database/

try this:
string database = (#"Data Source=(LocalDB)\v11.0;AttachDbFilename=E:\gip_stap_2\loonberekening.mdf;Integrated Security=True;Connect Timeout=30");
string werknemergegevens = "insert into tblWerknemer (naam,voornaam) values (#Naam,#Voornaam)";
using(SqlConnection cnnLoonberekening = new SqlConnection(database))
{
SqlCommand scmdLoon = new SqlCommand(werknemergegevens, cnnLoonberekening);
scmdLoon.Parameters.Add("#Naam",SqlDbType.VarChar).Value=txtNaam.Text;
scmdLoon.Parameters.Add("#Voornaam",SqlDbType.VarChar).Value=txtVoornam.Text;
scmdLoon.ExecuteNonQuery();
}

Related

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");
}

Getting column information in SQL

I am somwhat new to SQL, so I am not sure I am going about this the right way.
I am trying to fetch data from my SQL Server database where I want to find out if checkedin is 1/0, but it needs to search on a specific user and sort after the newest date as well.
What I am trying to do is something like this:
string connectionString = ".....";
SqlConnection cnn = new SqlConnection(connectionString);
SqlCommand checkForInOrOut = new SqlCommand("SELECT CHECKEDIN from timereg ORDER BY TIME DESC LIMIT 1 WHERE UNILOGIN = '" + publiclasses.unilogin + "'", cnn);
So my question, am I doing this right? And how do I fetch the data collected, if everything was handled correctly it should return 1 or 0. Should I use some sort of SqlDataReader? I am doing this in C#/WPF
Thanks
using (SqlDataReader myReader = checkForInOrOut.ExecuteReader())
{
while (myReader.Read())
{
string value = myReader["COLUMN NAME"].ToString();
}
}
This is how you would read data from SQL, but i recommend you looking into Parameters.AddWithValue
There are some errors in your query. First WHERE goes before ORDER BY and LIMIT is an MySql keyword while you are using the Sql Server classes. So you should use TOP value instead.
int checkedIn = 0;
string cmdText = #"SELECT TOP 1 CHECKEDIN from timereg
WHERE UNILOGIN = #unilogin
ORDER BY TIME DESC";
string connectionString = ".....";
using(SqlConnection cnn = new SqlConnection(connectionString))
using(SqlCommand checkForInOrOut = new SqlCommand(cmdText, cnn))
{
cnn.Open();
checkForInOrOut.Parameters.Add("#unilogin", SqlDbType.NVarChar).Value = publiclasses.unilogin;
// You return just one row and one column,
// so the best method to use is ExecuteScalar
object result = checkForInOrOut.ExecuteScalar();
// ExecuteScalar returns null if there is no match for your where condition
if(result != null)
{
MessageBox.Show("Login OK");
// Now convert the result variable to the exact datatype
// expected for checkedin, here I suppose you want an integer
checkedIN = Convert.ToInt32(result);
.....
}
else
MessageBox.Show("Login Failed");
}
Note how I have replaced your string concatenation with a proper use of parameters to avoid parsing problems and sql injection hacks. Finally every disposable object (connection in particular) should go inside a using block

How to get length of a specific column in a table

I am trying to get the length of a specific column in a table which table is from a database called Users in a visual studio C# form application. First of all i know it has to do with the column.length command but since those examples i have a searched i got lost.
Can someone tell me a simple way to get this happen? For more specific information i have a table called user_info and it contains a column which name is searches. I want to get the length of searches into a single variable
Here is the C# code that you need to pull the column size from the database. Make sure you update the connString variable to contain your own SQL server connection string.
Example: "Persist Security Info=False;Integrated Security=true;Initial Catalog=Northwind;server=(local)"
Int32 columnSize = 0;
string sql = "SELECT CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'user_info' AND COLUMN_NAME = 'searches'";
string connString = "Your Sql Server Connection String";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
columnSize = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

MySQL truncate command with parameter not working

Why do I get an exception when trying to truncate a MySQL table (using MySQL Connector/Net)? I am trying to give the table name with a parameter.
This is the code I'm executing:
var connectionString = "Server="+_server+";Uid="+_user+";Pwd="+_password+";Database="+_database+";";
try
{
using (var conn = new MySqlConnection(connectionString))
{
conn.Open();
const string sql = "TRUNCATE TABLE #tablename"; // also tried with TRUNCATE #tablename
var cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#tablename", "test");
cmd.ExecuteNonQuery();
conn.Close();
}
}
catch (MySqlException ex)
{
Console.WriteLine(ex.ToString());
}
And this is the execption:
MySql.Data.MySqlClient.MySqlException (0x80004005): You have an error
in your SQ L syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near ''test'' at line 1
When I try a select query, for example, then I don't have any problems. This runs fine and returns correct data:
conn.Open();
const string sql = "SELECT body FROM test WHERE id=#pid";
var cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#pid", 1);
cmd.ExecuteScalar();
conn.Close();
Parameters are used for query values, not object names like tables.
So this will not work for sure.
You need to set the table name in the command string by using string concatenation. You can avoid sql injection attacks by manually checking for weird characters in the table name (spaces, dashes, semicolons, etc..)
I've been playing around with this for a while now, and i can't seem to get it to work either. I can't find any documentation online, so i'm starting to think you may not be able to truncate with a parameter like you've tried.
However, is there really a need to prevent SQL injection on this command? Does the user enter the name of the table they want to truncate, and if so, they're just going to truncate a table which...is essentially what the command does anyway?

No data is inserted into my table

I have a simpe table:
Users
UserID Guid doesnt allow null
Avatar image allows null
Reputation int allows null
I used the following statement:
string insertCommand = "INSERT INTO Users (UserID) VALUES" +""+ "('"+UsersIdentityToinsert+"')";
UsersIdentityToinsert(this value is a Guid, I checked its value, it isn't null).
There were no exceptions thrown. As soon as the user presses the login button, he is transfered to another page, and his record is inserted.
I followed with the debugging that that statement is executed.
When I return to my server explorer in Visual Studio 2010 and click refresh the Users table is empty. Why is that?
Connection string
<add name="YourGuruDB" connectionString="Data Source=DIMA-00AA1DA557;Initial Catalog=model;Integrated Security=True"/>
i retrieve it from config into the code:
WebConfigurationManager.ConnectionStrings["YourGuruDB"].ConnectionString;
Added:
public static void InsertUsers(Guid UsersIDentity)
{
SqlConnection sqlConnect = getSqlConnection();
SqlCommand sqlCommand = new SqlCommand(RegisterAdo.insertCommand(UsersIDentity), sqlConnect);//insert command method returns the insert statement described above
try
{
sqlConnect.Open();
sqlCommand.ExecuteNonQuery();
}
catch (Exception x)
{
HttpContext.Current.Response.Redirect("~/ErrorPage.aspx?Error=" + WRITE_ERROR);
}
finally
{
sqlConnect.Close();
}
}
Instead of using
"INSERT INTO Users (UserID) VALUES" +""+ "('"+UsersIdentityToinsert+"')";
use this:
"INSERT INTO Users (UserID) VALUES" +""+ "(CONVERT(uniqueidentifier, '"+UsersIdentityToinsert+"'))";
And you really should use a prepared Statement instead of concatenating the sql.
What about the DB-connection? Did you run any successfull statements so far? Try a simple select.
try this :
"INSERT INTO Users (UserID) VALUES ('"+UsersIdentityToinsert+"')";
There are a number of things to check
Are you connected to the right database?
Is the code that executes this SQL Statement actually working. You don't show that code. I'd be expecting a ExecuteNonQuery() on a SqlCommand object somewhere.
Do you actually open a connection to a database? Or is the connection string just in the config without being used anywhere in your code?
Also, your code is susceptible to a SQL Injection attack. You should use a parameterised query to prevent that. This article on SQL Injection Attacks will help you with how to write that.
You also have missing code which I'd expect to see. Something along the lines of this:
string insertCommand = "INSERT INTO Users (UserID) VALUES"
+""+ "('"+UsersIdentityToinsert+"')";
string cs = WebConfigurationManager.ConnectionStrings["YourGuruDB"].ConnectionString;
SqlConnection conn = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(insertCommand, conn);
conn.Open();
cmd.ExexuteNonQuery();
conn.Close();

Categories