SQL Server CE string errors on .dbo. syntax - c#

A following question to this SO question
I'm using a SQL Server CE database included in the c# winforms project
The following does not work but if I amend the SQL string to
SELECT * FROM helloworld
then it does work. Why? Is there a full path that I could use
SELECT * FROM <blah>.<blah>.helloworld
?
using (var conn = new SqlCeConnection(ConfigurationManager.ConnectionStrings["DatabaseDGVexperiments.Properties.Settings.DatabaseDGVexperimentsConnStg"].ConnectionString))
{
conn.Open();
using (var myAdapt = new SqlCeDataAdapter("SELECT * FROM experiment.dbo.helloworld", conn))
{
DataSet mySet = new DataSet();
myAdapt.Fill(mySet, "AvailableValues");
DataTable myTable = mySet.Tables["AvailableValues"];
this.uxExperimentDGV.DataSource = myTable;
}
}

SQL CE doesn't have multiple schemas/catalogs like SQL Server (ref Thomas Levesque Jun 9)
Therefore no further information will ever be required in the FROM clause

Related

How to fetch the data Two service based sql server in C#

I have to retrive the data from one service based sql server to another service based sql server
select * from servernameA.db_name.dbo.table_name
where column in (select column from servernameb.db_name.dbo.table_name)
So what's the problem? You can do it.
Just a little performance improvement in your query with DISTINCT.
select * from servernameA.db_name.dbo.table_name
where column in (select DISTINCT column from servernameb.db_name.dbo.table_name)
For your reference:
Query across multiple databases on same server
Selecting data from two different servers in SQL Server
------------Edit----------------
How about this? I haven't tried this yet. Give this a try.
// connectionString is the connection string for the ServerA..DB1
using (var conn = new SqlConnection(connectionString))
{
conn.Open();
// provide commandText as the SQL query having the full name of Server2..DB2
using (var command = new SqlCommand(commandText, conn))
{
using (var reader = command.ExecuteReader())
{
while(reader.Read())
{
// read the result
}
}
}
}

Cross database query in C# to get Databases names list

I'm using Entity Framework 6 (EF6) with C#. I'm trying to write a DB agnostic query to get all the databases names list.
For example:
with SQL Server exists something like
select * from master.sys.databases
WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb');
with MySQL
SHOW DATABASES
and so on with Postgres, Oracle, etc.
So the question is if EF6 offers a way to get this list independently by the specific database.
You can do this :
public bool TestConnection(string connString, List<string> databases) {
using (context = new DatabaseContext(connString)) {
if (!context.Database.Exists())
return false;
string query = "select * from master.sys.databases WHERE name NOT IN('master', 'tempdb', 'model', 'msdb')";
var connection = context.Database.Connection;
DataTable dt_databases = new DataTable();
SqlDataAdapter dataAdapter = new SqlDataAdapter(query, connection.ConnectionString);
dataAdapter.Fill(dt_databases);
// Getting name from each dataRow
foreach (DataRow dr in dt_databases.Rows)
databases.Add(dr.ItemArray[0].ToString());
return true;
}
}
if you just want the name of databases, you can build your query like this:
string query = "select name from master.sys.databases WHERE name NOT IN('master', 'tempdb', 'model', 'msdb')";

How can I insert/update rows with C# to SQL Server

I am quit busy turning a old classic asp website to a .NET site. also i am now using SQL Server.
Now I have some old code
strsql = "select * FROM tabel WHERE ID = " & strID & " AND userid = " & struserid
rs1.open strsql, strCon, 2, 3
if rs1.eof THEN
rs1.addnew
end if
if straantal <> 0 THEN
rs1("userid") = struserid
rs1("verlangid") = strID
rs1("aantal") = straantal
end if
rs1.update
rs1.close
I want to use this in SQL Server. The update way. How can I do this?
How can I check if the datareader is EOF/EOL
How can I insert a row id it is EOF/EOL
How can I update a row or delete a row with one function?
If you want to use raw SQL commands you can try something like this
using (SqlConnection cnn = new SqlConnection(_connectionString))
using (SqlCommand cmd = new SqlCommand())
{
cnn.Open();
cmd.Connection = cnn;
// Example of reading with SqlDataReader
cmd.CommandText = "select sql query here";
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
myList.Add((int)reader[0]);
}
}
// Example of updating row
cmd.CommandText = "update sql query here";
cmd.ExecuteNonQuery();
}
It depends on the method you use... Are you going to use Entity Framework and LINQ? Are you going to use a straight SQL Connection? I would highly recommend going down the EF route but a simple straight SQL snippet would look something like:
using (var connection = new SqlConnection("Your connection string here"))
{
connection.Open();
using (var command = new SqlCommand("SELECT * FROM xyz ETC", connection))
{
// Process results
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
int userId = (int)reader["UserID"];
string somethingElse = (string)reader["AnotherField"];
// Etc, etc...
}
}
}
// To execute a query (INSERT, UPDATE, DELETE etc)
using (var commandExec = new SqlCommand("DELETE * FROM xyz ETC", connection))
{
commandExec.ExecuteNonQuery();
}
}
You will note the various elements wrapped in using, that is because you need to release the memory / connection when you have finished. This should answer your question quickly but as others have suggested (including me) I would investigate Entity Framework as it is much more powerful but has a learning curve attached to it!
You can use SQL store procedure for Update. And call this store procedure through C#.
Create procedure [dbo].[xyz_Update]
(
#para1
#para2
)
AS
BEGIN
Update tablename
Set Fieldname1=#para1,
Set Feildname2=#para2
end

Basic start with Visual Studio C# and SQL Compact (connect, select, insert)?

I'm trying to learn about C# with SQL CE so that my program can remember stuff.
I have created a database and can connect to it:
SqlCeConnection conn =
new SqlCeConnection(#"Data Source=|DataDirectory|\dbJournal.sdf");
conn.Open();
And it connects right, I guess cause if I rename the dbJournal.sdf to something wrong it doesn't debug right.
Let's say I want to make a simple SELECT query.
(SELECT * FROM tblJournal)
How is that done?
What about a simple insert?
(INSERT TO tblJournal (column1, column2, column2) VALUES
(value1, value2, value3))
I'm used to PHP and MySQL (as you properly can see :o))
#Chuck mentions EntityFramework which simplifies things and does all the work of writing the sql for you.
But there is a basic ADO.NET approach here which I will describe below.
The classes follow a standard pattern so to insert/read from sql server or other databases there are exact replica classes like SqlConnection or OleDbConnection and OleDbCommand etc
This is the most barebones ado.net approach:
using( SqlCeConnection conn =
new SqlCeConnection(#"Data Source=|DataDirectory|\dbJournal.sdf") )
using( SqlCeCommand cmd = conn.CreateCommand() )
{
conn.Open();
//commands represent a query or a stored procedure
cmd.CommandText = "SELECT * FROM tblJournal";
using( SqlCeDataReader rd = cmd.ExecuteReader() )
{
//...read
}
conn.Close();
}
Then to read data :
while (rd.Read())
{//loop through the records one by one
//0 gets the first columns data for this record
//as an INT
rd.GetInt32(0);
//gets the second column as a string
rd.GetString(1);
}
A nice and quicker way to read data is like this:
using( SqlCeDataAdapter adap =
new SqlCeDataAdapter("SELECT * FROM tblJournal", "your connection") )
{
//the adapter will open and close the connection for you.
DataTable dat = new DataTable();
adap.Fill(dat);
}
This gets the entire data in one shot into a DataTable class.
To insert data :
SqlCeCommand cmdInsert = conn.CreateCommand();
cmdInsert.CommandText = "INSERT TO tblJournal (column1, column2, column2)
VALUES (value1, value2, value3)";
cmdInsert.ExecuteNonQuery();
If you just start learning that i will suggest you to use LINQ to make that queries.
Here is MSDN article showing features of LINQ.
http://msdn.microsoft.com/en-us/library/bb425822.aspx
Using LINQ it will be simple to do every query. For example, you can write your select query like this
from journal in TblJournal select journal
or just
context.TblJournal
also in order to improve performence , you better keep the conncection open all the time when working with SQL CE (as opposed to other standard sql databases)

C# 'select count' sql command incorrectly returns zero rows from sql server

I'm trying to return the rowcount from a SQL Server table. Multiple sources on the 'net show the below as being a workable method, but it continues to return '0 rows'. When I use that query in management studio, it works fine and returns the rowcount correctly. I've tried it just with the simple table name as well as the fully qualified one that management studio tends to like.
using (SqlConnection cn = new SqlConnection())
{
cn.ConnectionString = sqlConnectionString;
cn.Open();
SqlCommand commandRowCount = new SqlCommand("SELECT COUNT(*) FROM [LBSExplorer].[dbo].[myTable]", cn);
countStart = System.Convert.ToInt32(commandRowCount.ExecuteScalar());
Console.WriteLine("Starting row count: " + countStart.ToString());
}
Any suggestions on what could be causing it?
Here's how I'd write it:
using (SqlConnection cn = new SqlConnection(sqlConnectionString))
{
cn.Open();
using (SqlCommand commandRowCount
= new SqlCommand("SELECT COUNT(*) FROM [LBSExplorer].[dbo].[myTable]", cn))
{
commandRowCount.CommandType = CommandType.Text;
var countStart = (Int32)commandRowCount.ExecuteScalar();
Console.WriteLine("Starting row count: " + countStart.ToString());
}
}
Set your CommandType to Text
command.CommandType = CommandType.Text
More Details from Damien_The_Unbeliever comment, regarding whether or not .NET defaults SqlCommandTypes to type Text.
If you pull apart the getter for CommandType on SqlCommand, you'll find that there's weird special casing going on, whereby if the value is currently 0, it lies and says that it's Text/1 instead (similarly, from a component/design perspective, the default value is listed as 1). But the actual internal value is left as 0.
You can use this better query:
SELECT OBJECT_NAME(OBJECT_ID) TableName, st.row_count
FROM sys.dm_db_partition_stats st
WHERE index_id < 2 AND OBJECT_NAME(OBJECT_ID)=N'YOUR_TABLE_NAME'

Categories