How can I see all databases in curent connection using ado.net? And then see all tables in each database.
it gets all database
it gets all tables from database(this link was deleted now use this one. but change code little)
ADO.Net : Get table definition from SQL server tables
you can iterate over database and get all tables
To list all databases you need to specify connection string without initial database. Then you can execute "sp_databases" stored procedure.
To list all tables in database you need to query INFORMATION_SCHEMA.Tables.
SAMPLES
To get databases:
System.Data.SqlClient.SqlConnection SqlCon = new System.Data.SqlClient.SqlConnection("server=192.168.0.1;uid=sa;pwd=1234");
SqlCon.Open();
System.Data.SqlClient.SqlCommand SqlCom = new System.Data.SqlClient.SqlCommand();
SqlCom.Connection = SqlCon;
SqlCom.CommandType = CommandType.StoredProcedure;
SqlCom.CommandText = "sp_databases";
System.Data.SqlClient.SqlDataReader SqlDR;
SqlDR = SqlCom.ExecuteReader();
while(SqlDR.Read())
{
Console.WriteLine(SqlDR.GetString(0));
}
To get tables:
string connectionString = "...";
DataTable tables = new DataTable("Tables");
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = "select table_name as Name from
INFORMATION_SCHEMA.Tables where TABLE_TYPE =
'BASE TABLE'";
connection.Open();
tables.Load(command.ExecuteReader(
CommandBehavior.CloseConnection));
}
In visual Studio 2010
Select View => Server Explorer
Then write server name, if you use SQL Server Authentication, select it, write your user name and password, select or enter a database name => OK
In the Server Explorer under the Data Connections you will see your database and tables.
Related
I am testing loads of records for my digital music files.
My add routine is:
foreach (AlbumModel albumModel in albs)
{
try
{
Album album = GetAlbum(albumModel);
cmd.CommandText = #"insert into CDS (title,artist,cddbid,genre,tracks,notes)
values (#title,#artist,#cddbid,#genre,#tracks,#notes)";
cmd.Parameters["#title"].Value = album.Title;
cmd.Parameters["#artist"].Value = album.Artist;
cmd.Parameters["#cddbid"].Value = album.Id;
cmd.Parameters["#genre"].Value = album.Genre.First().ToString();
cmd.Parameters["#tracks"].Value = album.Tracks.Count();
//cmd.Parameters["#image"].Value = GetCover(album.Title);
cmd.Parameters["#notes"].Value = GetNotes(album);
cmd.ExecuteNonQuery();
cmd.CommandText = #"Select ##Identity";
var retval = cmd.ExecuteScalar();
}
catch (Exception e)
{
string err = e.Message;
}
}
This works fine and I can see the records with a simple load of a datatable. However, using SQL Server Management Studio and connecting to the same express database on my machine a simple select * from CDS doesn't show any records at all.
Am I missing something?
using (SqlConnection connection = new SqlConnection(conn))
{
using (SqlDataAdapter adapter = new SqlDataAdapter("select * from CDS order by title", connection))
{
adapter.Fill(dt);
}
}
I am not using a transaction.
The connection string is:
#"Data Source = MyPC\SQLEXPRESS;Initial Catalog=Music;Integrated Security=true"
Which is the exact same one for SSMS.
The classical problem is that you insert the data while using a transaction and you don't commit the transaction. You could try
select * from CDS with (READUNCOMMITTED) order by title
from the sql management. In that way you can see the uncommitted row in open transactions.
(clearly if that is the problem then you have to modify your code to commit the transaction!)
may be you open a sql transaction and not commit it. after
var retval = cmd.ExecuteScalar();
add this line
YourTansaction.Commit();
YourTansaction.Dispose();
YourConnection.Close();
In Object explorer of the SQL server, navigate to the table you are inserting from the program and right click -> select "Select top 1000 rows". Thanks
I was wondering if it is possible for the update button to save the changes made in the table. I wrote this code but I have no idea how it could possibly work
This is the code i wrote for the update button:
string conString = "Data Source=MIRANDA-PC;Initial Catalog=Futebol do Rosa;Integrated Security=True";
SqlConnection con = new SqlConnection(conString);
string selectSql = "Update Players$ set Player Name='" + dataGridView2.Text + "";
SqlCommand cmd = new SqlCommand(selectSql, con);
con.Open();
This is the table I want to update the values in:
Well, you just need to execute your query with ExecuteNonQuery.
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 SqlConnection and SqlCommand.
And if your table or column names more than one word, you need to use them with [] as [Player Name]. And honestly, it is a little bit weird to use $ sign in a table name.
using(SqlConnection con = new SqlConnection(conString))
using(SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "Update Players$ set [Player Name] = #name";
cmd.Parameters.Add("#name", SqlDbType.NVarChar, 16).Value = dataGridView2.Text;
con.Open();
cmd.ExecuteNonQuery();
}
You have to execute your SQL query with your db object.
dbinstance.ExecuteSqlCommand(string sqlcommand, object[] params);
This method is both for DDL and DML.
you can also use ExecuteNonQuery method.
cmd.CommandText = "Update Players$ set [Player Name] = #Playername";
cmd.Parameters.Add("#Playername", SqlDbType.NVarChar, 16).Value = dataGridView2.Text;
con.Open();
cmd.ExecuteNonQuery();
The best solution (if possible) to to convert your DAL (Data Access Layer) to Entity-framework based, instead of writing your own SQL queries. This is safe-by-design and never is vulnerable to SQL Injection of any kind.
Here is some mockup code:
using (AppEntities currDb = new AppEntities)
{
Players PlayerToEdit =
from player in currDb.Players
where player.PlayerID == lngPlayerID
select player.First();
PlayerToEdit.PlayerName = dataGridView2.Text;
currDb.SaveChanges();
}
You can read about it some more here:
https://msdn.microsoft.com/en-us/data/ef.aspx
I have a connection string to connect to a database in C#. Which works and I am able to read/write to the database. However I am trying to get table names using the command
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = FC_TABLE;
When I use this command in SQL Server query I have to point to DB using 'USE DatabaseName GO' which is all well and good. If not then it queries Master and I get a return value that is empty.
However when I use this string in C# SqlReader I have already set the 'Initial Catalog' to the database I would normall point to with USE in my connection string so shouldn't it default there? I am getting the same empty return value but can't figure out why unless I have to use USE. But I am not having problems writing data otherwise.
This works for me. piv is my table name
using (SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog=temp;User ID=sa"))
{
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'piv';";
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string x = reader.GetString(0);
}
}
}
USE DATABASE_NAME is used in SQL Query editor where all the code line below to the USE statement would execute in that particular database. Creating connection string with a specific database in C# allows user to do operations only to that database unless you not mentioned any database explicitly in your query.
using(SqlConnection connection = new SqlConnection("server=.;Integrated Security=SSPI;Database=MyDB"))
{
string query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Resource';";
SqlCommand cmd = new SqlCommand(query, connection);
connection.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader.GetString(0));
}
}
}
Change your query to this. Remove GO and terminate query with semi colon;
var sql =#" Use Master
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME =#FC_DATASET;"
command.Parameters.AddWithValue("#FC_Dataset",yourTable);
I need a solution to transfer all data from SQL Server CE to Access mdb database.
I tried this approach http://www.codeproject.com/Answers/483989/HowplustoplusExportplusSQLplusTablesplusToplusAcce#answer2 (solution # 2) but getting an error "No database specified in connection string or IN clause."
The code works if I connect to non-compact SQL server.
I guess the problem is with connection string in IN clause but I cannot figure out how to change it.
Here is my code:
private void ExportTable(string tableName, string source, string destination)
{
var connStr = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}", destination);
var cmdText = string.Format("SELECT * INTO {0} FROM [{0}] IN ''[Data Source={1};Max Database Size='4000';Persist Security Info=False;];", tableName, source);
using (var conn = new OleDbConnection(connStr))
{
conn.Open();
using (var cmd = new OleDbCommand(cmdText, conn))
{
cmd.ExecuteNonQuery(); // error on this line
}
conn.Close();
}
}
The connection string: Data Source={1};Max Database Size='4000';Persist Security Info=False; working ok when I connect to the database directly.
UPDATE: Apparently the format of the source DB in IN Clause should be as following:
[type; DATABASE = path]
(see: http://answers.microsoft.com/en-us/office/forum/office_2010-access/access-2010-runtime-error-3170-could-not-find/0b085797-618a-488f-b1b4-30af00f04b3f)
When I use
var cmdText = string.Format("SELECT * INTO {0} FROM [{0}] IN ''[SqlServer CE; DATABASE={1}];", tableName, source);
I am getting different error: Could not find installable ISAM.
Do you know correct type for SQLServer CE? Is it supported at all? I could not find any info about it.
I have also tried: SQL CE, SQLSERVER.CE, Microsoft.SQLSERVER.CE.OLEDB.3.5, Microsoft.SQLSERVER.MOBILE.OLEDB.3.0 etc. - Same error...
I think the stumbling block here is that the trick you are trying to use requires an ODBC connection to the SQL Server and as far as I know there is no ODBC driver for SQL Server Compact. I'm pretty sure that the syntax [ODBC;Driver=...] in Access has no OLEDB equivalent, so the trick won't work with SQL Server Compact. (As you discovered, it does work with "real" SQL Server because ODBC connections are supported for that platform.)
I was curious to see what I could accomplish in C# using an OLEDB connection to the SQL Server Compact database (which is supported, as #MrZak pointed out in his comment). I came up with the following. It pulls the SQL table into a DataTable, sets the status of each row to "Added", and then updates (inserts into) the corresponding table in Access.
string myConnectionStringMDB =
"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source=C:\Users\Gord\Desktop\fromCE.mdb;";
string myConnectionStringSQL =
"Provider=Microsoft.SQLSERVER.CE.OLEDB.3.5;" +
#"Data Source=C:\Users\Public\test\myData.sdf;";
using (OleDbConnection conSQL = new OleDbConnection(),
conMDB = new OleDbConnection())
{
conSQL.ConnectionString = myConnectionStringSQL;
conSQL.Open();
conMDB.ConnectionString = myConnectionStringMDB;
conMDB.Open();
using (OleDbCommand cmdSQL = new OleDbCommand(),
cmdMDB = new OleDbCommand())
{
cmdSQL.CommandType = System.Data.CommandType.Text;
cmdSQL.Connection = conSQL;
cmdSQL.CommandText = "SELECT * FROM [Table1]";
var daSQL = new System.Data.OleDb.OleDbDataAdapter(cmdSQL);
var dt = new System.Data.DataTable();
daSQL.Fill(dt);
foreach (System.Data.DataRow dr in dt.Rows)
{
// change row status from "Unchanged" to "Added" so .Update below will insert them
dr.SetAdded();
}
cmdMDB.CommandType = System.Data.CommandType.Text;
cmdMDB.Connection = conMDB;
cmdMDB.CommandText = "SELECT * FROM [Table1]";
var daMDB = new System.Data.OleDb.OleDbDataAdapter(cmdMDB);
var cbuilderMDB = new OleDbCommandBuilder(daMDB);
cbuilderMDB.QuotePrefix = "[";
cbuilderMDB.QuoteSuffix = "]";
daMDB.Update(dt);
}
conSQL.Close();
conMDB.Close();
}
I'm still new to this, but "private void" from what I understand cant be imported or exported. Its only readable in that class or as a executable.
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