How to use local db project work on different pc - c#

I have been trying to use local db of c# and I have managed to work with local db. My db contains a connection string which is used by this command
SqlConnection _connection = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=F:\Devjeet Projects\Visual Studio Projects\Pujo Project\FinalPujoSetup\FinalPujoSetup\counter_db.mdf;Integrated Security=True");
I can see the path of the connection string contains the path somewhere in my pc. I am able to access the data with these queries.
For updating the database
_connection.Open();
SqlCommand cmd = _connection.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update [Table] set Time = '" + _new_time + "'";
cmd.ExecuteNonQuery();
_connection.Close();
and for fetching the data.
_connection.Open();
String sqlSelectQuery = "SELECT * FROM [Table] WHERE Id = " + int.Parse("1");
SqlCommand cmd = new SqlCommand(sqlSelectQuery, _connection);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
lblTotalTime.Text = (dr["Time"].ToString());
}
_connection.Close();
In this line lblTotalTime.Text = (dr["Time"].ToString()); the Time is the only table data.
Now I want to transfer this project to my friends pc and run it there. Obviously, it will not work because the path will be different.
is there any way I can change the connection string such that it can automatically fetch the path of the database in any computer and then can be executed there?
or is there any other way that I could use local db such that when I transfer the application in different pc, my application will work?

Related

Adapting C# code for SQL linked server to work directly with Sybase

I have an application written in C# that utilizes a linked server in MS SQL Server. The linked server hosts a Sybase database. I have code that successfully performs a lookup in a table on the linked server, but I have recently been instructed to access the linked server directly, due to performance issues.
I would like to share the code that worked correctly with use of a linked server in the hope that my intention can be easily understood. Then I would like some help on where I am failing to correctly write this to work with Sybase. I readily admit part of the problem is that I'm new to this. This is my first C# application.
private SqlConnection con = new SqlConnection();
int ScanCheck(string Agin, string UCC)
{
//This will open the SQL database connection for checking the
//variables 'Agin' and 'UCC' as lookup values for a single record
//containing both (defined and populated in an earlier part of the code).
//Stored procedure "ScanCheck" is executed. If a record is found, variable #Scans will be
//assigned a value of 1.
//establish connection to db
con.ConnectionString = Properties.Settings.Default.setDBPath;
con.Open();
//set up the sql command to increment hit count.
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "ScanCheck";
cmd.Parameters.AddWithValue("#Agin", Agin);
cmd.Parameters.AddWithValue("#UCC", UCC);
cmd.Parameters.AddWithValue("#Scans", SqlDbType.Int).Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
int Scans = Convert.ToInt32(cmd.Parameters["#Scans"].Value);
cmd.Dispose();
return Scans;
}
//The code above works as intended.
//Here is my attempt to access Sybase directly. I get an error at the line cmd.ExecuteNonQuery();
private AseConnection con = new AseConnection();
int ScanCheck(string Agin, string UCC)
{
con.ConnectionString = Properties.Settings.Default.TMS;
con.Open();
AseCommand cmd = new AseCommand();
cmd.Connection = con;
cmd.CommandTimeout = 0;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select #Scans = count(1) from Database.dbo.Table where whsl_agin_nbr = #Agin and mstr_ucc_cd = #UCC";
cmd.Parameters.AddWithValue("#Agin", Agin);
cmd.Parameters.AddWithValue("#UCC", UCC);
cmd.Parameters.AddWithValue("#Scans", AseDbType.Integer).Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
int Scans = Convert.ToInt32(cmd.Parameters["#Scans"].Value);
cmd.Dispose();
return Scans;
}
The error I receive is:
Sybase.Data.AseClient.AseException {"Unsupported parameter type"}

How to save a string in SQL Server as SqlDateType by using Visual Studio 2013?

How to save a string in SQL Server as SqlDateType by using Visual Studio 2013? My string which I want to save is 1996-25-04. I am working with C#.
I have tried this as far
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=sms;Persist Security Info=True;User ID=sa;Password=pass");
con.Open();
string sql = " insert into Staff_Management values( '" + TM_Add_BirthDate.Value.ToString() + "' ";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data saved successfully");
You should NEVER EVER concatenate together your SQL statements like this! This opens all doors to SQL injection attacks - and causes trouble with string and date values.
Try this code instead - using a parametrized query:
// define the query - and I'd recommend to always define the name of the columns you're inserting into
string query = "INSERT INTO dbo.Staff_Management(name-of-column-here) VALUES (#Birthdate);";
// define connection and command
// also: do **NOT** use the `sa` user for your production code!
using (SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=sms;Persist Security Info=True;User ID=sa;Password=pass"))
using (SqlCommand cmd = new SqlCommand(query, con))
{
// add the parameter - and use the proper datatype - don't convert all dates to strings all the time!
cmd.Parameters.Add("#Birthdate", SqlDbType.Date).Value = TM_Add_Birthdate.Value;
// open connection, execute INSERT query, close connection - done
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data saved successfully");
}

Can't write to SQLite database in WPF project

Having one of those tear-your-hair-out evenings.
I'm porting a WPF project over from using access and OleDBConnection to using SQLite and SQLiteConnection. My application reads from the project upon load, and then writes to it later after some form entry.
The reading works fine, using this code:
private void InitialiseDB()
{
connString = "data source = PortalDB.db";
conn = new SQLiteConnection(connString);
SQLiteCommand AttendeeCmd = new SQLiteCommand("SELECT * FROM AttendeeNames", conn);
SQLiteCommand SignInOutsCmd = new SQLiteCommand("SELECT SignTime, UserID, SignType FROM SignInOuts", conn);
conn.Open();
SQLiteDataAdapter AttendeeAdapter = new SQLiteDataAdapter(AttendeeCmd);
SQLiteDataAdapter SignInOutsAdapter = new SQLiteDataAdapter(SignInOutsCmd);
//Clear current datatables
AttendeeNamesTable.Clear();
SignInOutsTable.Clear();
//Fill data tables from adapters
AttendeeAdapter.Fill(AttendeeNamesTable);
SignInOutsAdapter.Fill(SignInOutsTable);
conn.Close();
}
But for the life of me I can't get the writing to work, It doesn't throw any errors or exceptions, it just doesn't write to the database. That code looks like this, with the data being passed in from having just been aded to a local DataTable:
private void SyncUpDB(int SignUserId, string SignType, DateTime SignTime)
{
//...Open the connection...
conn.Open();
//..Make SQL query by declaring fields to write to (not SignID) and where to get the data from. Strings need single quote, numbers do not.
String SyncUpDBQuery = "INSERT INTO SignInOuts (SignTime,UserID,SignType) VALUES('" + SignTime + "', " + SignUserId + ", '" + SignType + "')";
//...Make new database command from query
SQLiteCommand SyncUpDBCommand = new SQLiteCommand(SyncUpDBQuery, conn);
//...And execute on database
SyncUpDBCommand.ExecuteNonQuery();
}
As I say, this used to work perfectly with Access, just won't play ball with SQLite... any ideas?

Executing SQl Queries in C# using CLR

I am using SQl CLR for parsing some table column. I want to execute the queries also in C# user defined function. Can somebody give an example to execute select and insert queries in the function?
Thank you in advance.
SqlConnection objSqlConn;
string connString = string.Empty;
connString = "Data Source=(local);Initial Catalog=DB;User ID=uname;pwd=pass;Password=pass";
objSqlConn = new SqlConnection(connString);
objSqlConn.Open();
string query = "Select count(*) FROM [DB].[dbo].[TableName]";
SqlCommand cmdTotalCount = new SqlCommand(query, objSqlConn);
cmdTotalCount.CommandTimeout = 0;
string TotalCountValue = cmdTotalCount.ExecuteScalar().ToString();
return TotalCountValue;
In CLR, you can use existing connection to run queries.
Simple, returning data to client:
var cmd = new SqlCommand("select * from [table]");
SqlContext.Pipe.ExecuteAndSend(cmd);
Returning data via SqlDataReader:
var con = new SqlConnection("context connection=true"); // using existing CLR context connection
var cmd = new SqlCommand("select * from table", con);
con.Open();
var rdr = cmd.ExecuteReader();
SqlContext.Pipe.Send(rdr);
rdr.Close();
con.Close();
Running other commands:
var con = new SqlConnection("context connection=true"); // using existing CLR context connection
var cmd = new SqlCommand("insert into [table] values ('ahoj')", con);
con.Open();
var rsa = cmd.ExecuteNonQuery();
con.Close();
Once you switch to C# you execute queries like you'd normally do from your application (using ADO.NET's SqlConnection and SqlDataReader, using LINQ to SQL or using your custom build data layer).
To connect with the database you have to mention the database username and password in the connection string of your web.config file.

inserting and deleting not happening in local database (.sdf)

When I try to select values from a local database it executes without any issue. But when I try to insert and delete it's executing the query but it's not affecting any rows.
This is the code I'm using to delete row from my local database:
SqlCeConnection sqlConnection1 = new SqlCeConnection();
sqlConnection1.ConnectionString = "Data Source = Database1.sdf";
SqlCeCommand cmd = sqlConnection1.CreateCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "DELETE FROM table1 WHERE slno=2";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.Prepare();
int aff=cmd.ExecuteNonQuery();//here its returning '0'
MessageBox.Show(aff.ToString());
sqlConnection1.Dispose();
sqlConnection1.Close();
It is possible that the delete won't affect any rows.
As an aside, I would advise using the using statement in your code:
using (SqlCeConnection conn = new SqlCeConnection("Data Source = Database1.sdf"))
using (SqlCeCommand comm = new SqlCeCommand("DELETE FROM table1 WHERE slno = 2", conn))
{
conn.Open();
comm.CommandType = CommandType.Text;
comm.ExecuteNonQuery();
}
This will handle disposal of relevant objects for you.
Assuming that the SQL is relevant to your database and that you have successfully connected using the connection string beforehand, then the above could will perform a delete action against your database.

Categories