Readonly database MDF file. Windows app - sql-server

can someone help me.
I've tried moving the MDF file around to different locations but I'm still unable to update the database. I'm using Windows 7.
Here's my code:
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace TestDatabase
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
System.Data.SqlClient.SqlConnection con;
DataSet ds1;
System.Data.SqlClient.SqlDataAdapter da;
int MaxRows = 0;
int inc = 0;
private void Form1_Load(object sender, EventArgs e)
{
con = new System.Data.SqlClient.SqlConnection();
ds1 = new DataSet();
con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\rebdog\\AppData\\MyWorkers.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
con.Open();
string sql = "SELECT * From tblWorkers";
da = new System.Data.SqlClient.SqlDataAdapter(sql, con);
MessageBox.Show("database Open");
da.Fill(ds1, "Workers");
NavigateRecords();
MaxRows = ds1.Tables["Workers"].Rows.Count;
con.Close();
MessageBox.Show("database closed");
}
private void btnSave_Click(object sender, EventArgs e)
{
System.Data.SqlClient.SqlCommandBuilder cb;
cb = new System.Data.SqlClient.SqlCommandBuilder(da);
DataRow dRow = ds1.Tables["Workers"].NewRow();
dRow[1] = textBox1.Text;
dRow[2] = textBox2.Text;
dRow[3] = textBox3.Text;
ds1.Tables["Workers"].Rows.Add(dRow);
MaxRows = MaxRows + 1;
inc = MaxRows - 1;
da.Update(ds1,"Workers");
}
}
}
The code is from a tutorial, I need to get this working before I add a database to my project.
Thank you guys.

According to your code (in the connection string) the mdf file should be in
C:\Users\rebdog\AppData\MyWorkers.mdf
The connection is set up to use integrated security, meaning that it uses your windows login to access that database. So if you have problems accessing the database, it might be because it requires another user account, or because your user doesn't have read/write access to that folder.

Related

xamarin cannot conect to sql server

the application must connect directly to the sql server database and output data from the table
I wrote the following code:
using Android.App;
using Android.OS;
using Android.Support.V7.App;
using Android.Runtime;
using Android.Widget;
using System.Data.SqlClient;
namespace PrApp4
{
[Activity(Label = "#string/app_name", Theme = "#style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
TextView textView1;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
textView1 = FindViewById<TextView>(Resource.Id.textView1);
string ConString = "Data Source=COMP106-1\\SQLEXPRESS;Initial Catalog=AVTO_SALON;";
string SqlCom = "select * from Avto";
using (SqlConnection sqlCon = new SqlConnection(ConString)) {
sqlCon.Open();
SqlCommand cmd = new SqlCommand(SqlCom, sqlCon);
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
//await DisplayAlert("Уведомление", reader.GetString(1), "ОK");
textView1.Text = reader.GetString(1);
//textView2.Text = reader.GetString(3);
}
}
}
}
when you start the application, the following error appears:
cannot connect to sql server browser ensure sql server browser has been started

How do I check for duplicates and remove them on each data entry in SQL Server, WPF, C#?

I'm practicing SQL integration in C# by creating a Zoo Management app. Users can input a new name of Zoo to be listed on a ListBox. I want the app to check whether the new zoo is already listed or not (checking for duplicates), and if there is a duplicate, it will remove the newly added zoo.
I can't figure out the SQL query to do that.
Here I create a tiny simulation app to ask about the duplicates removing method.
Table name is TEST with just 2 columns Id and Name.
In the WPF there is a ListBox which lists all names, 2 buttons (Add and Remove names), and one TextBox to type in the want-to-be added name.
I've tried various methods and I just can't seem to get it to work.
public partial class MainWindow : Window
{
SqlConnection sqlConnection;
public MainWindow()
{
string connectionString = ConfigurationManager.ConnectionStrings["DeleteDuplicateTest.Properties.Settings.DB1ConnectionString"].ConnectionString;
sqlConnection = new SqlConnection(connectionString);
InitializeComponent();
ShowNames();
}
// This is where I got lost
public void CheckForDuplicates()
{
}
public void ShowNames()
{
string query ="select * from TEST";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(query, sqlConnection);
using (sqlDataAdapter)
{
DataTable names = new DataTable();
sqlDataAdapter.Fill(names);
listNames.DisplayMemberPath = "Name";
listNames.SelectedValuePath = "Id";
listNames.ItemsSource = names.DefaultView;
}
}
private void Add_Click(object sender, RoutedEventArgs e)
{
if (myTextBox.Text != "")
{
string query = "Insert into TEST values (#Name)";
SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
sqlConnection.Open();
sqlCommand.Parameters.AddWithValue("#Name", myTextBox.Text);
sqlCommand.ExecuteScalar();
sqlConnection.Close();
ShowNames();
CheckForDuplicates();
}
}
private void Remove_Click(object sender, RoutedEventArgs e)
{
if (listNames.SelectedValue != null)
{
string query = "Delete from TEST where Id=#Name";
SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
sqlConnection.Open();
sqlCommand.Parameters.AddWithValue("#Name", listNames.SelectedValue);
sqlCommand.ExecuteScalar();
sqlConnection.Close();
ShowNames();
CheckForDuplicates();
}
}
}

While Uploading the Excel sheet table to SQL server table $ is not uploading with numbers but upload with text only

i want to upload the excel sheets data to the sql sever 2008, all my data i.e numbers and Alphabets from my excel sheet table are going to upload in the Database table but $ sign is not going to upload there as i have to use a currency as a column, $sign going to upload with text data but not with numbers.....pls let me knw abt this problem
this is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Xml;
using System.Configuration;
using System.IO;
using log4net.Config;
using log4net;
namespace ExcelUpload
{
class Program
{
static ILog log = LogManager.GetLogger(typeof(Program));
//Variable declarations
public static string strSqlConnection, strExcelDataQry, strSqlTable, strExcelFilePath, sexcelconnectionstring;
public static int intRows;
static void Main(string[] args)
{
#region GET PARAMS FROM CONFIG FILE
strSqlConnection = ConfigurationManager.ConnectionStrings["SQLConnection"].ToString();
strExcelFilePath = ConfigurationManager.AppSettings["ExcelFileName"].ToString();
string[] sqlSheets = ConfigurationManager.AppSettings["Sheets"].Split(',');
#endregion
#region SET CONNECTIONS
sexcelconnectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strExcelFilePath + ";Extended Properties='Excel 12.0 xml;HDR=YES;'";
SqlConnection Sqlconn = new SqlConnection(strSqlConnection);
SqlBulkCopy bulkcopy = new SqlBulkCopy(strSqlConnection);
OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
#endregion
XmlConfigurator.Configure();
log4net.ThreadContext.Properties["Context"] = "ExcelUpload";
try
{
log.Info("Started Execution of ExcelUpload Process");
foreach (string sqlSheetName in sqlSheets)
{
#region GET PARAMS FROM CONFIG FILE BASED ON CURRENT SHEET
strExcelDataQry = "select " + ConfigurationManager.AppSettings[sqlSheetName + "ColumnNames"] + " from [" + sqlSheetName + "$]";
strSqlTable = ConfigurationManager.AppSettings[sqlSheetName + "Table"];
intRows = Convert.ToInt32(ConfigurationManager.AppSettings[sqlSheetName + "RowsToExclude"].ToString());
#endregion
#region TRUNCATE TABLE
SqlCommand SqlCommand = new SqlCommand("TRUNCATE TABLE " + strSqlTable, Sqlconn);
Sqlconn.Open();
SqlCommand.ExecuteNonQuery();
Sqlconn.Close();
log.Info("Table " + strSqlTable + " Truncated Successfully");
#endregion
#region BULK COPY DATA
log.Info("Started processing the sheet " + sqlSheetName);
OleDbCommand oledbcmd = new OleDbCommand(strExcelDataQry, oledbconn);
oledbconn.Open();
DataSet ds = new DataSet();
using (OleDbDataAdapter adapter = new OleDbDataAdapter(oledbcmd))
{
adapter.Fill(ds);
}
for (int iRow = 0; iRow < intRows; iRow++)
{
ds.Tables[0].Rows[iRow].Delete();
}
ds.Tables[0].AcceptChanges();
foreach (DataRow dr in ds.Tables[0].Rows)
{
foreach (DataColumn col in ds.Tables[0].Columns)
{
if (col.DataType == typeof(System.String))
{
dr[col] = dr[col].ToString().Trim();
}
}
}
bulkcopy.DestinationTableName = strSqlTable;
bulkcopy.WriteToServer(ds.Tables[0]);
oledbconn.Close();
log.Info("Sheet " + sqlSheetName + " successfully loaded to the table " + strSqlTable);
#endregion
}
log.Info("ExcelUpload Process completed successfully");
}
catch (System.Exception ex)
{
log.Info("Error while processing :- " + ex.Message);
}
finally
{
Sqlconn.Close();
oledbconn.Close();
}
}
}
}
If you want the currency column as Int you cant insert the $ symbols and decimal in it because defaultly integer datatype won't allow it.
So, to solve your problem make the curreny as Varchar and insert the data as something like $100.00
and while displaying it just show it.
And while doing calculations in front end remove the $ symbol using Contains keyword
and convert it into Double and do your calculations.
Hope it helps
Ok try this link for storing the data from excel to gridview(just for an example), you just change your need.
I also tested with that code to store the data which contains $ symbol in the cells and store it in the database also displaying the same data from the database with $ symbols in the same cells.
Have a look at it, it may be useful.
Load Gridview from Excel
just change the code for your need.

Change DataBase using DataGrid

I want to output data from DataBase to DataGrid, using ADO.NET.
Can you tell me how to do that?
When I'm writing something in dataGrid it's changing in database. I use WPF, .NET 4.0.
Code:
class ThemeEditor
{
private SqlDataAdapter da;
private DataSet ds;
private SqlConnection cn;
public ThemeEditor(DataGrid dg)
{
SqlCommand cmd;
string source = "server=(local); integrated security=SSPI; database=tests";
string reqest = "SELECT Theme,Stuff FROM Themes";
cn = new SqlConnection(source);
da = new SqlDataAdapter();
ds = new DataSet();
cmd = new SqlCommand(reqest, cn);
da.SelectCommand = cmd;
da.Fill(ds, "Theme");
dg.ItemsSource = ds.Tables["Theme"].DefaultView;
}
}
maybe it'll be helpfull!
http://support.microsoft.com/kb/307587
or this... http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/3adacd01-f08f-4059-bbce-bff736a5188e

Access to SQL Server messages via ADO.NET

Is it possible to access the SQL Server "by-product messages" via ADO.NET? Due to the lack of words, by "by-product messages" I mean the output which appears in the Messages tab in Microsoft SQL Server Management Studio. What I particularly have it mind is to read the output of SET STATISTICS TIME ON. It appears that SqlDataReader does not offer anything in this matter.
Yes, there's an event on the SqlConnection class called SqlInfoMessage, which you can hook into:
SqlConnection _con =
new SqlConnection("server=.;database=Northwind;integrated Security=SSPI;");
_con.InfoMessage += new SqlInfoMessageEventHandler(InfoMessageHandler);
The event handler will look like this:
static void InfoMessageHandler(object sender, SqlInfoMessageEventArgs e)
{
string myMsg = e.Message;
}
The e.Message is the message printed out to the message window in SQL Server Management Studio.
Thank you for the response above. I just did a little experiment and found a little unexpected glitch (a bug?) when reading messages (in this case produced by SET STATISTICS TIME ON) from a multi-recordset result. As indicated below, one has to call NextResult even after the last resultset in order to get the last message. This is not needed in the case of a single recordset result.
using System;
using System.Data.SqlClient;
namespace TimingTest
{
class Program
{
static void Main(string[] args)
{
SqlConnection conn = new SqlConnection("some_conn_str");
conn.Open();
conn.InfoMessage += new SqlInfoMessageEventHandler(Message);
SqlCommand cmd = new SqlCommand("some_sp", conn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read()) { };
rdr.NextResult();
while (rdr.Read()) { };
// this is needed to print the second message
rdr.NextResult();
rdr.Close();
conn.Close();
}
static void Message(object sender, SqlInfoMessageEventArgs e)
{
Console.Out.WriteLine(e.Message);
}
}
}
Based on marc_s' answer, I ve created a wrapper class
public class SqlInfoMessageWrapper
{
public SqlInfoMessageWrapper(SqlConnection connection)
{
SqlConnection = connection;
connection.InfoMessage += new SqlInfoMessageEventHandler(InfoMessageHandler);
}
public SqlConnection SqlConnection { get; set; }
public string Message { get; set; }
void InfoMessageHandler(object sender, SqlInfoMessageEventArgs e)
{
Message = e.Message;
}
}
Example of use :
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
var messageWrapper=new SqlInfoMessageWrapper(connection) ;
var ret = SqlHelper2.ExecuteNonQuery(connection, CommandType.Text, command, null);
messages+= $"{messageWrapper.Message} number of rows affected {ret} ";
}

Resources