Software is not working when MS SQL server version is changed - c#

I'm using SQL Server 2005 database - server in my software (OS-XP). When I changed the server to SQL Server 2008 (OS-windows 7), the software didn't work.
I debugged the program and found Array index out of bounds exception in a part of a code, when I changed that code its working fine, can anyone please tell me what is the reason for the problem?
String cnnStr = String.Format("Data Source = {0}; Initial Catalog = {1}; Integrated Security = SSPI; persist security info=False; Trusted_Connection=Yes",ServerName, Databasae);
sqlConnection = new SqlConnection(cnnStr);
sqlConnection.Open();
Original code
Server server = new Server(new ServerConnection(sqlConnection));
Database db = server.Databases[Databasae];
Table Table = new Table(db, TableName);
Column TimeColumn = new Column(Table, "DateTime");
TimeColumn.DataType = DataType.DateTime;
TimeColumn.Nullable = false;
Column ValueColumn = new Column(Table, "Value");
ValueColumn.DataType = DataType.Float;
ValueColumn.Nullable = false;
Table.Columns.Add(TimeColumn);
Table.Columns.Add(ValueColumn);
Table.Create();
New code
StringBuilder query = new StringBuilder();
query.Append("CREATE TABLE ");
query.Append(TableName);
query.Append(" ( [DateTime] DateTime , Value float(10) )");
SqlCommand sqlQuery = new SqlCommand(query.ToString(), sqlConnection);
SqlDataReader reader = sqlQuery.ExecuteReader();
reader.Close();

You need to update your SMO SDK to the SQL 2008 version and remove all of the 2005 references as you are no longer using SQL 2005.
You can read a bit more on the subject here:
http://msdn.microsoft.com/en-us/library/ms162129.aspx

Related

System.Data.SqlClient.SqlException: 'Invalid object name when trying to insert data in database (C#, Visual Studio)

First I would like to say that I thought that my problem was easily solved but after a lot of trying and searching I am not making any progress (I am also a complete beginner when it comes to databases).
I made a database with Microsoft SQL Server and called it UltimatePokerDB.
I added a table MyTable
I added two columns sevenKeys and sevenValues
this is visible in Visual Studio
Image of my Server Explorer in visual studio
and makes this SQL code
CREATE TABLE MyTable
(
[sevenKeys] BINARY(56) NOT NULL PRIMARY KEY,
[SevenValues] BINARY(48) NOT NULL
)
I have the following code written in my Main method
string provider = "System.Data.SqlClient";
string connectionstring = "Server=localhost;Database=master;Trusted_Connection=True;";
byte[] one = new byte[7];
byte[] two = new byte[6];
DbProviderFactory factory = DbProviderFactories.GetFactory(provider);
using (SqlConnection cnn = new SqlConnection(connectionstring))
{
string sql = "insert into MyTable (sevenKeys, sevenValues) values(#first,#last)";
cnn.Open();
using (SqlCommand cmd = new SqlCommand(sql, cnn))
{
cmd.Parameters.AddWithValue("#first", one);
cmd.Parameters.AddWithValue("#last", two);
cmd.ExecuteNonQuery();
Console.WriteLine("row inserted");
}
}
I get an error at cmd.ExecuteNonQuery() and it says: System.Data.SqlClient.SqlException: 'Invalid object name 'MyTable'.'
Basically Im giving it the wrong name but I have no clue what it wants me to do...
You've specified in your connection string to use the Database master. You should probably be using the database your table is in, which is probably not master. In fact it looks like it should be UltimatePokerDB from your screenshot.

How to get data table without using database name in query

I tried to get table which has top record from Oracle database through ODBC driver. For this, I am using below code.
OdbcConnectionStringBuilder builder = new OdbcConnectionStringBuilder();
builder.ConnectionString = "Driver={Oracle in OraClient11g_home1};Dbq=localhost;Uid=system;Pwd=abc;Database = NORTHWIND";
OdbcConnection con = new OdbcConnection();
con.ConnectionString = builder.ConnectionString;
con.Open();
string query = "SELECT \"NORTHWIND\".\"ORDERS\".\"ID\" AS \"My field id\" FROM \"NORTHWIND\".\"ORDERS\" WHERE ROWNUM = 1";
OdbcCommand cmd = new OdbcCommand(query,con);
var k = cmd.ExecuteReader();
var datatable = new DataTable();
datatable.Load(k);
con.Close();
The above code is working fine for me. I need to execute query without database name. Here database name is NORTHWIND. But If I am using query without database name like "SELECT \"ORDERS\".\"ID\" AS \"My field id\" FROM \"ORDERS\" WHERE ROWNUM = 1"
I got an exception "table or view does not exist."
Even if my connectionstring has database name, I got this exception.
Can anyone explain me why I got the above exception when using query without database name?
Change your connection string to this-
builder.ConnectionString = "Driver={Oracle in OraClient11g_home1};Dbq=localhost;Uid=system;Pwd=abc;Data Source = NORTHWIND;";
Referrences-
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.initialcatalog(v=vs.110).aspx
http://www.c-sharpcorner.com/UploadFile/nipuntomar/connection-strings-for-oracle/
https://docs.oracle.com/database/121/ODPNT/featConnecting.htm#ODPNT199

Why do added records not show up in SQL Server management studio using SQL Serve Express?

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

How to Export Data from SQL server Compact To Access MDB

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.

Showing information about databases in ado.net

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.

Categories

Resources