How to save data from local sdf database into text file? - c#

Is there any possibility to save data from local sdf database into text file in C# ? I don't have any idea how to do it and unfortunettly I don't have a lot of time.. each row of the database must be in new line of text file

You must do it manually (i.e. by code). MS SQL CE does not provide the import/export features that the SQL Server editions do.

this is from an old project of mine it works. just change the name of the table "tableProduit" with the name of your choice. if you run into problems ask ....
using System;
using System.Data.SqlServerCe;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using System.Data;
namespace app
{
class Connexion
{
SqlCeConnection conn;
string connectionString;
string chemin;
public Connexion(string path,string password)
{
this.chemin = path;
connectionString = string.Format("DataSource={0}", this.chemin + ";Password="+password);
conn = new SqlCeConnection(connectionString);
}
public bool isConnected()
{
try
{
conn.Open();
}catch(SqlCeException e){
MessageBox.Show(e.ToString());
return false;
}
bool temp = false;
SqlCeDataReader dr;
SqlCeCommand cmd = new SqlCeCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM tableProduit";
dr = cmd.ExecuteReader();
if (dr.Read())
{
temp = true;
}
else
{
temp = false;
}
dr.Close();
conn.Close();
return temp;
}
public void writeData(string filepath,string filetype)
{
conn.Open();
SqlCeDataReader dr;
SqlCeCommand cmd = new SqlCeCommand();
SqlCeDataAdapter adpt = new SqlCeDataAdapter();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM tableProduit";
dr = cmd.ExecuteReader();
adpt.SelectCommand = cmd;
if (filetype == "txt")
{
TextWriter writer = new StreamWriter(filepath);
while (dr.Read())
{
writer.WriteLine(dr["codeBarre"] + ":" + dr["qte"]);
}
writer.Close();
}
else
{
//Create the data set and table
DataSet ds = new DataSet("New_DataSet");
DataTable dt = new DataTable("New_DataTable");
//Set the locale for each
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
adpt.Fill(dt);
ds.Tables.Add(dt);
}
dr.Close();
conn.Close();
}
}
}
Edit : forget about the fileds writer.WriteLine(dr["codeBarre"] + ":" + dr["qte"]); change them to the names of your fields.good luck

Related

C# connection to oracle DB

I am trying to get a select result and write a simple authentication. But i have some problems with reader.HasRows/table.Rows.Count>0, its always false. Maybe reason not in reader/adapter, but i dont have other ideas
Form1.cs[enter image description here][1]
private void button1_Click(object sender, EventArgs e)
{
String loginUser = loginField.Text;
String paswwordUser = passwordField.Text;
DB db = new DB();
DataTable table = new DataTable();
OracleDataAdapter adapter = new OracleDataAdapter();
OracleCommand command = new OracleCommand();
command.CommandType = CommandType.Text;
command.CommandText = "SELECT * from users where login='#uL' AND pass = '#uP' ";
command.Parameters.Add("#uL", OracleDbType.Varchar2).Value = loginUser;
command.Parameters.Add("#uP", OracleDbType.Varchar2).Value = paswwordUser;
command.Connection = db.GetConnection();
db.openConnection();
// OracleDataReader reader = command.ExecuteReader();
adapter.SelectCommand = command;
table.Load(command.ExecuteReader());
adapter.Fill(table);
if (table.Rows.Count>0)
MessageBox.Show("Yes");
else
MessageBox.Show("No");
// reader.Close();
}
DB.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Oracle.DataAccess.Client;
{
class DB
{
OracleConnection connection = new OracleConnection("Data Source=****/XEPDB1;User Id=****;Password=****;");
public void openConnection()
{
if (connection.State == System.Data.ConnectionState.Closed)
connection.Open();
}
public void closeConnection()
{
if (connection.State == System.Data.ConnectionState.Open)
connection.Close();
}
public OracleConnection GetConnection()
{
return connection;
}
}
}
https://i.stack.imgur.com/8m5ZZ.jpg
try to use colon:
command.CommandText = "SELECT * from users where login=:uL AND pass = :uP ";
command.Parameters.Add("uL", OracleDbType.Varchar2).Value = loginUser;
command.Parameters.Add("uP", OracleDbType.Varchar2).Value = paswwordUser;
command.Connection = db.GetConnection();
db.openConnection();
DataSet dataSet = new DataSet();
using (OracleDataAdapter dataAdapter = new OracleDataAdapter())
{
dataAdapter.SelectCommand = command;
dataAdapter.Fill(dataSet, "Users");
}
var dataTable= dataSet.Tables["Users"];
this.BindingContext[dataTable].EndCurrentEdit();
if(dataSet.HasChanges(DataRowState.Modified))
{
// do your stuff here
}

Can't retrieve data from database and store into a value

I am currently working on a forum project using a gridview to attached the data to the database. Using SelectedIndexChanged, it will redirect to another page to display the details in labels. However, I am unable to display & there isn't any specific error.
This is my code:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class FAQViewPost : System.Web.UI.Page
{
string _connStr = ConfigurationManager.ConnectionStrings["WingsDrinksDbContext"].ConnectionString;
FAQ faq = null;
string CustQuestionCategory = null;
string CustQuestion = null;
protected void Page_Load(object sender, EventArgs e)
{
string FAQID = Request.QueryString["FAQID"].ToString();
Load(FAQID);
}
protected void Load(string FAQID)
{
DataTable dt = new DataTable();
string queryStr = "SELECT * FROM [FAQ] WHERE FAQID = #FAQID ";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand();
string[] arr = { queryStr };
string allQueries = string.Join(";", arr);
cmd.CommandText = allQueries;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#FAQID", FAQID);
SqlDataAdapter sqlDa = new SqlDataAdapter(cmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
lbl_category.Text = dt.Rows[0]["CustQuestionCategory"].ToString();
lbl_question.Text = dt.Rows[0]["CustQuestion"].ToString();
}
conn.Close();
conn.Dispose();
}
}
I do not know why you are putting the SQL into an array. You only have one statement. Try using just:
DataTable dt = new DataTable();
string queryStr = "SELECT * FROM [FAQ] WHERE FAQID = #FAQID ";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = queryStr;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#FAQID", FAQID);
SqlDataAdapter sqlDa = new SqlDataAdapter(cmd);
sqlDa.Fill(dt);
I presume you have checked that the FAQ table has a record for the id you are sending? Also life would be a bit safer if you used numeric ids.

Set datatables to be equivalent

This is probably a simple question but I am not experienced in C#.
I have 2 datatables, 1 is basically a copy of the other (like a table to review information). To set the values this is what I am doing now:
string attribute1 = "";
string attribute2 = "";
string attribute3 = "";
.....
DataTable result = new DataTable();
using (SqlConnection con = new SqlConnection("user id=user_id;password=pwd;server=serverstring;Trusted_Connection=yes;database=database;connection timeout=30"))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM table1 WHERE parameter=#identifying_parameter", con))
{
cmd.Parameters.AddWithValue("#identifying_parameter", "example");
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
attribute1 = Convert.ToString(reader["attribute1"]);
attribute2 = Convert.ToString(reader["attribute2"]);
attribute3 = Convert.ToString(reader["attribute3"]);
.....
}
con.Close();
}
}
using (SqlConnection con = new SqlConnection("user id=user_2;password=pwd;server=serverstring;Trusted_Connection=yes;database=database;connection timeout=30"))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO table2 (attribute1, attribute2, attribute3, ...) VALUES(#attribute1, #attribute2, #attribute3, ...)", con))
{
cmd.Parameters.AddWithValue("#attribute1", attribute1);
cmd.Parameters.AddWithValue("#attribute2", attribute2);
cmd.Parameters.AddWithValue("#attribute3", attribute3);
....
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(result);
con.Close();
da.Dispose();
}
}
Obviously I might have a lot of attributes, so is there a simpler way to set every attribute in the table to be equal in C#?
You can use INSERT..INTO..SELECT
DataTable result = new DataTable();
using (SqlConnection con = new SqlConnection("user id=user_2;password=pwd;server=serverstring;Trusted_Connection=yes;database=database;connection timeout=30"))
{
using (SqlCommand cmd = new SqlCommand(#"INSERT INTO table2 (attribute1, attribute2, attribute3, ...)
SELECT attribute1, attribute2, attribute3 ... FROM table1
WHERE parameter=#identifying_parameter
", con))
{
cmd.Parameters.AddWithValue("#identifying_parameter", "example");
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(result);
con.Close();
da.Dispose();
}
}
You can use * instead of specifying the column name, although which is not good practice..
In order to make a second Table identical (or "equivalent" as per your definition) to the first one (for certainty let's call it sourceTable), you can use SqlBulkCopy.WriteToServer Method (DataTable)(re: https://msdn.microsoft.com/en-us/library/ex21zs8x%28v=vs.110%29.aspx)
using (SqlConnection YourConnection= new SqlConnection(YourConnectionString))
{
YourConnection.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(YourConnection))
{
bulkCopy.DestinationTableName = "dbo.YourDestinationTable";
try
{
// Write from the source to the destination.
bulkCopy.WriteToServer(sourceTable);
}
catch (Exception ex) { }
}
}
In order to get a sourceTable you can use the following code snippet:
DataTable sourceTable = SqlReadDB(YourConnString, "SELECT *")
private static DataTable SqlReadDB(string ConnString, string SQL)
{
DataTable _dt;
try
{
using (SqlConnection _connSql = new SqlConnection(ConnString))
{
using (SqlCommand _commandl = new SqlCommand(SQL, _connSql))
{
_commandSql.CommandType = CommandType.Text;
_connSql.Open();
using (SqlCeDataReader _dataReaderSql = _commandSql.ExecuteReader(CommandBehavior.CloseConnection))
{
_dt = new DataTable();
_dt.Load(_dataReaderSqlCe);
_dataReaderSql.Close();
}
}
_connSqlCe.Close();
return _dt;
}
}
catch { return null; }
}
}
Hope this may help.

Visual Studio Query Database from Variable DataGridView

I have been trying to query a access database and displaying the results in a DataDrigView. The grid displays all the data when I use the "SELECT * FROM CustomerPayments". However once I try adding a Parameter to the query I get an error message by
adapter.Fill(ds); //No value given for one more required parameters
However I have already successfully use a query using a parameter in another part of my program, it only seems to happen when I want to display in a data grid
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.SqlClient; //Import database class
namespace WindowsFormsApplication1
{
public partial class frmCustomerDetails : Form
{
//Database
//Get connection from database
String connectionString = staticConnectionString.connectionString;
//Declare a connection object
OleDbConnection con;
//Declare a command object for the SQL
OleDbCommand cmd;
//Declare an accedd type reader to read SQL commands
OleDbDataReader dr;
String[] CustomerID = new String[500];
String[] CustomerName = new String[500];
String[] Street = new String[500];
String[] Area = new String[500];
String[] PostCode = new String[500];
String[] TelNo = new String[500];
String[] Email = new String[500];
int RecordNo = 0;
int LastRecord = 0;
public frmCustomerDetails()
{
InitializeComponent();
}
private void frmCustomerDetails_Load(object sender, EventArgs e)
{
try
{
//create a connection object to the database via string location
con = new OleDbConnection(connectionString);
//Open the connection to the database
con.Open();
//Creat a new command object
cmd = new OleDbCommand();
//Set the SQL command text
cmd.CommandText = "SELECT * FROM Customer WHERE CustomerID = #ID;";
cmd.Parameters.AddWithValue("#ID", GlobalVar.SelectedCustomer);
//Link the command to the connection so the correct DB is used
cmd.Connection = con;
//Run the command and store resulting table in the datareader
dr = cmd.ExecuteReader();
}
catch (Exception err)
{
//Any database errors jump here and output error message
MessageBox.Show("A database error has occurred: " + Environment.NewLine + err.Message);
}
finally
{
//Do this whatever happens
//This is so the first record will be displayed
//Connection and dr are left open until from closes so more records can be accessed
}
//dr.Read() gets the next in the results if possible
while (dr.Read())
{
//Fill the text boxes with data
CustomerID[RecordNo] = dr["CustomerID"].ToString();
CustomerName[RecordNo] = dr["Names"].ToString();
Street[RecordNo] = dr["Street"].ToString();
Area[RecordNo] = dr["Area"].ToString();
PostCode[RecordNo] = dr["PostCode"].ToString();
TelNo[RecordNo] = dr["TelNo"].ToString();
Email[RecordNo] = dr["Email"].ToString();
RecordNo = RecordNo + 1;
}
LastRecord = RecordNo;
RecordNo = 0;
ReadDisplay();
}
private void btnMenu_Click(object sender, EventArgs e)
{
var SelectCustomer = new frmSelectCustomer();
SelectCustomer.Show();
this.Close();
}
private void btnWeeklyOrders_Click(object sender, EventArgs e)
{
String connectionString = staticConnectionString.connectionString;
OleDbCommand command;
OleDbDataAdapter adapter;
con = new OleDbConnection(connectionString);
command = con.CreateCommand();
//create data set
DataSet ds = new DataSet();
//Clear the gride of data
CustomerInfo.DataSource = null;
//create a new dataset
ds = new DataSet();
//Open connection
con.Open();
//Run the query
command.CommandText = "SELECT * FROM CustomerPayments WHERE CustomerID = #ID;";
cmd.Parameters.AddWithValue("#ID", GlobalVar.SelectedCustomer);
adapter = new OleDbDataAdapter(command);
adapter.Fill(ds);
//close connection
con.Close();
//Populate grid with data
CustomerInfo.DataSource = ds.Tables[0];
}
private void ReadDisplay()
{
lblCustomerID.Text = CustomerID[RecordNo];
lblNames.Text = CustomerName[RecordNo];
lblStreet.Text = Street[RecordNo];
lblArea.Text = Area[RecordNo];
lblPostCode.Text = PostCode[RecordNo];
lblTelNo.Text = TelNo[RecordNo];
lblEmail.Text = Email[RecordNo];
}
}
}
You assigning parameter for incorrect OleDbCommand variable:
command.CommandText = "SELECT * FROM CustomerPayments WHERE CustomerID = #ID;";
cmd.Parameters.AddWithValue("#ID", GlobalVar.SelectedCustomer);
should be:
command.CommandText = "SELECT * FROM CustomerPayments WHERE CustomerID = #ID;";
command.Parameters.AddWithValue("#ID", GlobalVar.SelectedCustomer);

SQLCommand syntax error

I am writing to request some help on my c# syntax. I keep getting syntax in "sda.Fill(dt);" and I can not figure out the reason why.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string query = "select distinct Price_type from Price";
DataTable dt = GetData(query);
ddlPrice.DataSource = dt;
ddlPrice.DataTextField = "Price_type";
ddlPrice.DataValueField = "Price_type";
ddlPrice.DataBind();
ddlPrice2.DataSource = dt;
ddlPrice2.DataTextField = "Price_type";
ddlPrice2.DataValueField = "Price_type";
ddlPrice2.DataBind();
ddlPrice2.Items[1].Selected = true;
}
}
protected void Compare(object sender, EventArgs e)
{
string query = string.Format("select price, date from Price where Price_type = '{0}' order by date)", ddlPrice.SelectedItem.Value);
DataTable dt = GetData(query);
string[] x = new string[dt.Rows.Count];
decimal[] y = new decimal[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
x[i] = dt.Rows[i][0].ToString();
y[i] = Convert.ToInt32(dt.Rows[i][1]);
}
LineChart1.Series.Add(new AjaxControlToolkit.LineChartSeries { Name = ddlPrice.SelectedItem.Value, Data = y });
query = string.Format("select price, date from Price where Price_type = '{0}' order by date)", ddlPrice2.SelectedItem.Value);
dt = GetData(query);
y = new decimal[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
x[i] = dt.Rows[i][0].ToString();
y[i] = Convert.ToInt32(dt.Rows[i][1]);
}
LineChart1.Series.Add(new AjaxControlToolkit.LineChartSeries { Name = ddlPrice2.SelectedItem.Value, Data = y });
LineChart1.CategoriesAxis = string.Join(",", x);
LineChart1.ChartTitle = string.Format("{0} and {1} Order Distribution", ddlPrice.SelectedItem.Value, ddlPrice2.SelectedItem.Value);
LineChart1.Visible = true;
}
private static DataTable GetData(string query)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["bwic testConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
date might be a reserved keyword, depending of the version you use. Write [date] instead. And this
"select price, date from Price where Price_type = '{0}' order by date)"
should be
"select price, date from Price where Price_type = '{0}' order by date"
You can try with this code
using (var con = new SqlConnection(constr))
{
using (var cmd = new SqlCommand(query))
{
using (var sda = new SqlDataAdapter())
{
con.Open();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
There's nothing syntactically wrong with your GetData() method as shown in your original post. You might try commenting out the entire body of the method and then start uncommenting things one at a time to isolate the actual problem.
But it apparently seems that you don't have a syntax error: you have invalid SQL. The SQL you are trying to execute is:
select price, date from Price where Price_type = '{0}' order by date)
It has two things wrong with it:
The closing (right) parenthesis at the end is your syntax error, and
the parameter should not be enclosed in quotes.
Your SQL should look something like
select price, date from Price where Price_type = {0} order by date
Your method should look something like this:
private static DataTable GetData1( string query , string p0 )
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["bwic testConnectionString"].ConnectionString;
using ( SqlConnection con = new SqlConnection( constr ) )
using ( SqlCommand cmd = con.CreateCommand() )
using ( SqlDataAdapter sda = new SqlDataAdapter(cmd) )
{
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
SqlParameter p = new SqlParameter() ;
p.Value = p0Value ;
cmd.Parameters.Add( p ) ;
con.Open();
sda.Fill( dt );
con.Close();
}
return dt;
}
Don't forget to use brackets twice - in SELECT clause and in ORDER BY clause too.
in your code bolck as below
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
change it to
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
con.Open();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
The problem here is that you havent opened any connection before filling.
You haven't opened a connection anywhere. You must open the connection before you can use it.
If your whole class code is really this, you are missing a closing } at the end of the file for the
public partial class Default2 : System.Web.UI.Page
{
declaration.

Categories

Resources