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);
}
}
Related
I am trying to store an image path in my mysql database but it does not store the backslash(/).
this is my path - string str = #"C:\Users\user\Downloads\99 Most Amazing Collection of Computer Desktop Wallpapers - 5522 [ECLiPSE]"
this is how it appears in mysql - C:UsersuserDownloads99 Most Amazing Collection of Computer Desktop Wallpapers - 5522 [ECLiPSE]
Because of this i am unable to retrive the image, so how do i store the imagepath with the backslash included.
Mysql Code
string sqlstring = "server=; port= ; user id =;Password=;Database=;";
string str = #"C:\Users\user\Downloads\99 Most Amazing Collection of
Computer Desktop Wallpapers - 5522 [ECLiPSE]"
MySqlConnection conn = new MySqlConnection(sqlstring);
try
{
conn.Open();
}
catch (MySqlException ex)
{
throw ex;
}
string Query = "INSERT INTO test.blogimagestable (ImagesId)values('" + str + "');";
MySqlCommand cmd = new MySqlCommand(Query, conn);
cmd.ExecuteReader();
conn.Close();
You should use parametrized queries to prevent such problems from happen automatically. And other nasty things, like SQL injections.
And you should rather call ExecuteNonQuery() instead of ExecuteReader() for a statement, that doesn't return a result. Or at least take care of calling Dispose() on the useless reader or using using. (Same goes for your other disposable objects.)
...
string Query = "INSERT INTO test.blogimagestable (ImagesId)values(?str);";
MySqlCommand cmd = new MySqlCommand(Query, conn)
cmd.Parameters.Add("?str", MySqlDbType.VarString, 256).Value = str;
cmd.ExecuteNonQuery();
...
Change the type and length passed to Parameters.Add() according to the type of your column.
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
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();
}
I'm diving head first into both C# and Access databases. This is all brand new to me, so I have a small test database set up to work with a small template. I'm trying to figure out why I keep getting a syntax error that is triggered by the ExecuteNonQuery() method. Any help and insight would be appreciated.
Edit: SOLVED: This is the working code for this situation. All help was greatly appreciated!
public void addToDb()
{
String first = "John";
String last = "Doe";
String testPath = GVar.TEST_FILEPATH + GVar.TEST_DATABASE;
String strCommand = "INSERT INTO ID ([First], [Last]) Values(#First, #Last)";
OleDbConnection dbTest = null;
OleDbCommand cmd = null;
try
{
dbTest = new OleDbConnection(GVar.OLE_DB_WRITE + testPath);
dbTest.Open();
cmd = new OleDbCommand(strCommand, dbTest);
cmd.Parameters.AddWithValue("#First", first);
cmd.Parameters.AddWithValue("#Last", last);
cmd.ExecuteNonQuery();
Console.WriteLine("Data Added");
}
catch (Exception ex)
{
Console.WriteLine("Db Test: " + ex.Message);
}
dbTest.Close();
}
From OleDbCommand.Parameters property
The OLE DB .NET Provider does not support named parameters for passing
parameters to an SQL statement or a stored procedure called by an
OleDbCommand when CommandType is set to Text. In this case, the
question mark (?) placeholder must be used. For example:
SELECT * FROM
Customers WHERE CustomerID = ?
Therefore, the order in which
OleDbParameter objects are added to the OleDbParameterCollection must
directly correspond to the position of the question mark placeholder
for the parameter in the command text.
I don't see anything wrong in your INSERT statement other than this.
cmd.CommandText = "INSERT INTO Identity ([First],[Last]) VALUES(?, ?)";
cmd.Parameters.AddWithValue("#First", first);
cmd.Parameters.AddWithValue("#Last", last);
cmd.ExecuteNonQuery();
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?