how to create user define tables by ADO.net - c#

A desktop-based software shall enable a user to create tables in a provided database as per requirement.
My problem is that ExecuteNonQuery treats only Data Manipulation Language.
What should i use for Data Definition Language, i.e to pass create command.
Thanks in advance :)
my code
3rd party edit
From the linked image
public void create(string name, int varchar_quantity, string rate)
{
con.Close();
string s = "Crate table anas('" + name + "' varchar ('"
+ varchar_quantity + "')" + rate + "' int);";
con.Open();
SqlCommand com = new SqlCommand(s, con);
com.ExecuteNonQuery();
}

You should be able to create tables with ExecuteNonQuery method.
From msdn documentation,
You can use the ExecuteNonQuery to perform catalog operations (for
example, querying the structure of a database or creating database
objects such as tables), or to change the data in a database without
using a DataSet by executing UPDATE, INSERT, or DELETE statements.
var conStr = "PUT YOUR CONNECTION STRING HERE";
using (var c = new SqlConnection(conStr))
{
c.Open();
var qry = "CREATE TABLE TEST(name varchar(30));";
using (var cmd = new SqlCommand(qry, c))
{
cmd.ExecuteNonQuery();
}
}

Related

Use Variable In SQL String

How can I add a variable to my SQL string and run it against the server successfully? I want to run this statement through my C#
protected void RunSQLQuery(string salesman, string connectionString)
{
SqlConnection cnn;
SqlCommand cmd;
StringBuilder sql = new StringBuilder();
SqlDataReader reader;
cnn = new SqlConnection(connectionString);
sql = new StringBuilder();
sql.Append("update database ");
sql.Append("set shippdate = GetDate() ");
sql.Append("where salesman = "' + salesman + "'");
sql.Append("and managerapproval is not null ");
cnn.Open();
cmd = new SqlCommand(sql.ToString(), cnn);
reader = cmd.ExecuteReader();
reader.Close();
cmd.Dispose();
cnn.Close
}
This presents multiple compile errors underlining my +salesman+ code. The errors are:
Only assignment, call, increment, decrement, and new object
expressions can be used as a statement
; expected
) expected
Too many characters in character literal Newline in constant
You are not adding the string object that salesman refers, you are adding salesman as a string literal.
Just add it as a parameter like;
var cmd = new SqlCommand("update database set shippdate = GetDate() where salesman = #salesman");
cmd.Parameters.Add("#salesman", salesman);
...
And use ExecuteNonQuery to execute your command, not SqlDataReader. This SqlDataReader is for return some data.
But more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your connection and command automatically instead of calling Close or Dispose methods manually.
As a full example;
protected void RunSQLQuery(string salesman, string connectionString)
{
using(var cnn = new SqlConnection(connectionString))
using(var cmd = cnn.CreateCommand())
{
cmd.CommandText = #"update database set shippdate = GetDate()
where salesman = #salesman";
// I assume your column is nvarchar
cmd.Parameters.Add("#salesman", SqlDbType.NVarChar).Value = salesman;
cnn.Open();
cmd.ExecuteNonQuery();
}
}
For myself, I always prefer to use SqlParameterCollection.Add(string, SqlDbType, Int32) overload to specify my parameter type and it's size but since you never mentioned your salesman column type, I couldn't post this in my example.
As you can also see from the syntax highlighting, the compile errors are caused because you did not escape the quotes properly in sql.Append("where salesman = "' + salesman + "'");.
As a side note, you should never insert strings into sql queries without first validating them, or you are open to sql injection, e.g. if i pass "''; drop table database;" as salesman parameter. It is better to use SqlParameter.
I would suggest using the AddWithValue method from your sql command combined with the UPPER function to make it case insensitive:
SqlCommand cmd = cnn.CreateCommand();
cmd.CommandText = "UPDATE database SET shippdate = GetDate() WHERE UPPER(salesman) = UPPER(#salesMan)";
cmd.Parameters.AddWithValue("#salesMan", salesman);
if (cnn.State.Equals(ConnectionState.Closed))
{
cnn.Open();
}
cmd.ExecuteNonQuery();
cnn.Close();
As mentioned in above answers, yes, writing queries in this way is not a good way to do it. But still if you want to do it that way only, you will have to change:
sql.Append("where salesman = "' + salesman + "'");
to
sql.Append("where salesman = '" + salesman + "'");

How to modify a constraint on a SQL Server table from c#?

I want to modify a constraint on a SQL Server table from C# code. Is it possible to do?
Please help.
Here is a sample code for update that I use.
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "UPDATE Student(LastName, FirstName, Address, City)
VALUES(#ln, #fn, #add, #cit) WHERE LastName='" + lastName + "' AND FirstName='" + firstName+"'";
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
var removeConstraint = "ALTER TABLE Customer DROP CONSTRAINT Con_First;";
var createConstraint = "ALTER TABLE Customer ADD CONSTRAINT Con_First UNIQUE (Address);";
var removeConstraintCmd = new SqlCommand(removeConstraint, conn);
removeConstraintCmd.ExecuteNonQuery();
var createConstraintCmd = new SqlCommand(createConstraint, conn);
createConstraintCmd.ExecuteNonQuery();
NOTE: conn is your connection
The script strings (top two variables) will be what you need to change but, in summary, you drop the constrain then recreate it.
As a side note, I'd be curious to see why you want to do this. You may have problems in your overall approach as this is not something typically done from ADO .net (depending on your scenario of course).

How to use auto indexing in ACCESS database using OleDb in C# with sql commands

I wrote a form based program in C# that uses MS access database to store its data.
In the MDB file I have a single table named __item__
in the table there are 7 fields of which the first one is called __item_id__ and it is the auto indexer of the table, so when I add new entry it should auto increase each time, so I won't have 2 entry's with the same id.
In the program I use the following code (this isn't the full code, just the relevant one):
using System.Data.OleDb;
private OleDbConnection con; // create connection
private OleDbCommand cmd; // create command
con = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = d:\\library0.1\\DB.mdb");
cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "INSERT INTO Item VALUES (#item_name, #creator_name,#publishing_name,#item_type,#genre,#year_publication);";
con.Open(); // open the connection
cmd.ExecuteNonQuery();
con.Close();
this code will give me an error __ExecuteNonQuery__ claiming I have too few fields.
It wants me to enter the __item_id__ manually, like this:
cmd.CommandText = "INSERT INTO Item VALUES (#item_id, #item_name, #creator_name,#publishing_name,#item_type,#genre,#year_publication);";
How can I avoid manual input and have the program auto index the item_id for each new entry?
If you use INSERT INTO without specifying the column list you should provide parameter for all columns.
To avoid the error change your commandtext to:
"INSERT INTO Item " +
"(item_name, creator_name publishing_name, item_type, genre, year_publication) " +
"VALUES " +
"(#item_name, #creator_name,#publishing_name,#item_type,#genre,#year_publication);";

Read\Write\Change MySql Table from asp.net list view

so, i am building a new website for my brother and it seems that i need to use MySql for him.
In ASP.NET there is a list view item, that you can choose from which DB is will take the info and you can Read \ Write \ Change \ Delete with a click of a button.
any one here know how can i do that with MySql ? and not mssql.. i know how to use DataBases, i just didnt ever worked with MySql and i will be thankfull for anyone who will help me.
Thanks again! alon.. :)
You first need a connector which you can find here
Then instead of using System.Data classes use the one you just downloaded. They are the same classes, but the only difference is that they are for MySQL.
Furthermore if you want to write MySQL queries, well they are pretty much the same as in MSSQL. Here are some examples:
Read:
SELECT id, value FROM table
WHERE id = 16;
Write:
INSERT INTO table(id, value)
VALUES (1,'Bob'),(2,'Betty');
Change:
UPDATE table
SET id = 7
WHERE id = 16;
Delete:
DELETE FROM table
WHERE id = 7;
And in your C# code you just need to use 3-4 classes to work with the database. Since I don't want to make this a wall of text, you can read more about those classes here , unless you are familiar enough with those.
Here is a general approach to do basic operations with mysql database. I assume that you know how to setup your mysql database. if not you can find many info about it on google. I also assumed that you have a table on your mysql database named "table" which has following columns: id, name, address.
// Connection String
private const string ConnStr =
"Driver={MySQL ODBC 3.51 Driver};Server=localhost;" +
"Database=test;uid=root;pwd=;option=3";
// DataBinding
private void BindDataGrid()
{
using(OdbcConnection con = new OdbcConnection(ConnStr))
using(OdbcCommand cmd =
new OdbcCommand("SELECT * FROM Sample", con))
{
con.Open();
DataGrid1.DataSource = cmd.ExecuteReader(
CommandBehavior.CloseConnection |
CommandBehavior.SingleResult);
DataGrid1.DataBind();
}
}
// Insert Operation
private void InsertInfo()
{
if(CheckIsAddNameValid())
{
HtmlTable2.Visible = false;
using(OdbcConnection con = new OdbcConnection(ConnStr))
using(OdbcCommand cmd = new OdbcCommand("INSERT INTO sample" +
"(name, address) VALUES (?,?)", con))
{
cmd.Parameters.Add("#name", OdbcType.VarChar,
255).Value = TextBox3.Text.Trim();
cmd. Parameters.Add("#address", OdbcType.VarChar,
255).Value = TextBox4.Text.Trim();
con.Open();
cmd.ExecuteNonQuery();
BindDataGrid();
}
}
}
// Update Operation
private void UpdateInfo(int id, string name, string address)
{
using(OdbcConnection con = new OdbcConnection(ConnStr))
using(OdbcCommand cmd = new OdbcCommand("UPDATE sample " +
"SET name = ?, address = ? WHERE ID = ?", con))
{
cmd.Parameters.Add("#name", OdbcType.VarChar, 255).Value = name;
cmd.Parameters.Add("#address",
OdbcType.VarChar, 255).Value = address;
cmd.Parameters.Add("#ID", OdbcType.Int).Value = id;
con.Open();
cmd.ExecuteNonQuery();
}
}
// Update Operation
private void DeleteInfo(int id)
{
using(OdbcConnection con = new OdbcConnection(ConnStr))
using(OdbcCommand cmd = new OdbcCommand("DELETE " +
"FROM sample WHERE ID = ?", con))
{
cmd.Parameters.Add("#ID", OdbcType.Int).Value = id;
con.Open();
cmd.ExecuteNonQuery();
}
}
if you do not have a table on your database use this script to create the database in this example:
CREATE TABLE sample (
id int AUTO_INCREMENT NOT NULL,
name varchar(45) NOT NULL,
address varchar(45) NOT NULL,
PRIMARY KEY(id)
)
GO
BindDataGrid function shows the result of the query in datagrid. In general you can put the result of any query to a list and then bind it to the datagrid with the following code:
List<string> AllStudents = getAllStudents();
dataGrid1.datasource = AllStudents;
dataGrid1.databind();
ASP.Net works with database through the Provider Model. You you have downloaded the ADOconnector for MySql, it should work the same way as how it is with MS SQL, except that you have to use different set of queries specific to MySql.
You might also try looking into the Entity Framework. It is an object-relational-mapper (ORM) which abstracts the tables of a database into objects that you can easily work with in code. It makes code much more readable and maintainable than hardcoding SQL strings (as some of the other answers suggest).
The Entity Framework is Microsoft's recommended solution. You can use it with the MySQL connector that Bosak pointed out.
NHibernate is another popular ORM you might want to look into.

ADO.Net : Get table definition from SQL server tables

I am using C# to write a method that returns the following information about a table:
column names, column types, column sizes, foreign keys.
Can someone point me in the right direction on how to accomplish this ?
This really depends on how you communicate with your database. If you are using LinqToSQL or another similar ORM this would be pretty easy but if you want to get these values via a query I'd suggest you use the INFORMATION_SCHEMA views as these are fast and easy to query.
e.g.
select * from information_schema.columns where table_name = 'mytable'
To get the FK and Schema you should be able to use:
DA.FillSchema()
DS.Table("Name").PrimaryKey
OR calling sp_fkey using the method demonstrated below
Code Snippet from AND Another Link
private void LoanSchema()
{
private List<String> tablesList = new List<String>();
private Dictionary<String, String> columnsDictionary = new Dictionary<String, String>();
string connectionString = "Integrated Security=SSPI;" +
"Persist Security Info = False;Initial Catalog=Northwind;" +
"Data Source = localhost";
SqlConnection connection = new SqlConnection();
connection.ConnectionString = connectionString;
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "exec sp_tables";
command.CommandType = CommandType.Text;
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
tablesList.Add(reader["TABLE_NAME"].ToString());
}
reader.Close();
command.CommandText = "exec sp_columns #table_name = '" +
tablesList[0] + "'";
command.CommandType = CommandType.Text;
reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
columnsDictionary.Add(reader["COLUMN_NAME"].ToString(), reader["TYPE_NAME"].ToString());
}
}
You can use the SqlDataAdapter.FillSchema() method.
Alternatively you can use the SqlDataAdapter.Fill() method after setting the MissingSchemaAction property of the SqlDataAdapter to AddWithKey. But if you only want the schema you must ensure that your query returns no rows. This can be accomplished by adding a statement like WHERE 1=2 to your query.
If you are using MS SQL Server then You should definately have a look at SMO namespace (server management objects).
There are objects which You can use in .net responsible for all kinds of things in a database (including but not limited to tables, columns, constraints etc.)
I think you need the System.Data.DataTable class:
http://msdn.microsoft.com/en-us/library/system.data.datatable.aspx

Categories

Resources