public void Init(string connection) { System.Data.SqlServerCe.SqlCeConnection con = new System.Data.SqlServerCe.SqlCeConnection(connection); actionAdapter.Connection = con; conditionAdapter.Connection = con; elementAdapter.Connection = con; recognitionAdapter.Connection = con; scriptAdapter.Connection = con; stepAdapter.Connection = con; usersAdapter.Connection = con; websiteAdapter.Connection = con; validationAdapter.Connection = con; scvta.Connection = con; usersAdapter.Fill(DB.users); recognitionAdapter.Fill(DB.recognition); elementAdapter.Fill(DB.element); websiteAdapter.Fill(DB.website); actionAdapter.Fill(DB.action); conditionAdapter.Fill(DB.condition); stepAdapter.Fill(DB.step); scriptAdapter.Fill(DB.script); validationAdapter.Fill(DB.validation); IsInitialized = true; }
private SqlCeConnection GetConnection() { //int empresa_id = int.Parse(file.Name.Split('_')[0]); //empresa = CntLainsaSci.GetEmpresa(empresa_id, ctx); //AppDomain.CurrentDomain.SetData("SQLServerCompactEditionUnderWebHosting", true); //SqlCeConnection conn = GetConnection(); //GuardarDispositivos(conn); //ctx.SaveChanges(); string conn = string.Format("Data Source={0};Password =;Persist Security Info=True", file); SqlCeEngine DBDatabase = new SqlCeEngine(conn); SqlCeConnection vCon = new System.Data.SqlServerCe.SqlCeConnection(conn); try { vCon.Open(); return(vCon); } catch (Exception VError) { ControlDeError(VError); } finally { DBDatabase.Dispose(); } return(null); }
private void button1_Click(object sender, EventArgs e) //save { System.Data.SqlServerCe.SqlCeConnection con = new System.Data.SqlServerCe.SqlCeConnection(); System.Data.SqlServerCe.SqlCeDataAdapter daHangmanDB; DataRow drow; DataSet dsSavedGames = new DataSet(); DataSet dsSavedGame_Words = new DataSet(); con.ConnectionString = "Data Source=HangmanDB.sdf"; con.Open(); daHangmanDB = new System.Data.SqlServerCe.SqlCeDataAdapter("SELECT * From SavedGames", con); daHangmanDB.Fill(dsSavedGames, "SavedGames"); con.Close(); if (dsSavedGames.Tables["SavedGames"].Rows.Count > 0) { drow = dsSavedGames.Tables["SavedGames"].Rows[dsSavedGames.Tables["SavedGames"].Rows.Count - 1]; latestID = System.Convert.ToInt32(drow[0]) + 1; } else { latestID = 0; } drow = dsSavedGames.Tables["SavedGames"].NewRow(); drow[1] = textBox1.Text; drow[2] = wins; drow[3] = losses; drow[4] = DateTime.Now; dsSavedGames.Tables["SavedGames"].Rows.Add(drow); con.Open(); System.Data.SqlServerCe.SqlCeCommandBuilder cb; cb = new System.Data.SqlServerCe.SqlCeCommandBuilder(daHangmanDB); cb.DataAdapter.Update(dsSavedGames.Tables["SavedGames"]); con.Close(); /*---------------------------------------------------------------------*/ con.Open(); daHangmanDB = new System.Data.SqlServerCe.SqlCeDataAdapter("SELECT * From SavedGame_Words", con); daHangmanDB.Fill(dsSavedGame_Words, "SavedGame_Words"); con.Close(); foreach (int id in wordsplayedimported) { drow = dsSavedGame_Words.Tables["SavedGame_Words"].NewRow(); drow[0] = latestID; drow[1] = id; dsSavedGame_Words.Tables["SavedGame_Words"].Rows.Add(drow); } con.Open(); cb = new System.Data.SqlServerCe.SqlCeCommandBuilder(daHangmanDB); cb.DataAdapter.Update(dsSavedGame_Words.Tables["SavedGame_Words"]); con.Close(); MessageBox.Show("Game Saved"); }
private void button1_Click(object sender, EventArgs e) { int selectedID = System.Convert.ToInt32(listView1.SelectedItems[0].SubItems[0].Text); wins = System.Convert.ToInt32(listView1.SelectedItems[0].SubItems[2].Text); losses = System.Convert.ToInt32(listView1.SelectedItems[0].SubItems[3].Text); System.Data.SqlServerCe.SqlCeConnection con = new System.Data.SqlServerCe.SqlCeConnection(); System.Data.SqlServerCe.SqlCeDataAdapter daHangmanDB; DataRow drow; DataSet dsSavedGame_Words = new DataSet(); con.ConnectionString = "Data Source=HangmanDB.sdf"; con.Open(); daHangmanDB = new System.Data.SqlServerCe.SqlCeDataAdapter("SELECT * From SavedGame_Words", con); daHangmanDB.Fill(dsSavedGame_Words, "SavedGame_Words"); con.Close(); for (int i = 0; i < dsSavedGame_Words.Tables["SavedGame_Words"].Rows.Count; ++i) { drow = dsSavedGame_Words.Tables["SavedGame_Words"].Rows[i]; if (System.Convert.ToInt32(drow[0]) == selectedID) { wordsplayed.Add(System.Convert.ToInt32(drow[1])); } } this.Close(); }
public LoadMenu() { InitializeComponent(); button1.DialogResult = DialogResult.OK; System.Data.SqlServerCe.SqlCeConnection con = new System.Data.SqlServerCe.SqlCeConnection(); System.Data.SqlServerCe.SqlCeDataAdapter daHangmanDB; DataRow drow; DataSet dsSavedGames = new DataSet(); con.ConnectionString = "Data Source=HangmanDB.sdf"; con.Open(); daHangmanDB = new System.Data.SqlServerCe.SqlCeDataAdapter("SELECT * From SavedGames", con); daHangmanDB.Fill(dsSavedGames, "SavedGames"); con.Close(); for (int i = 0; i < dsSavedGames.Tables["SavedGames"].Rows.Count; ++i) { drow = dsSavedGames.Tables["SavedGames"].Rows[i]; ListViewItem listItem = new ListViewItem(System.Convert.ToString(drow[0])); listItem.SubItems.Add(System.Convert.ToString(drow[1])); listItem.SubItems.Add(System.Convert.ToString(drow[2])); listItem.SubItems.Add(System.Convert.ToString(drow[3])); listItem.SubItems.Add(System.Convert.ToString(drow[4])); listView1.Items.Insert(0, listItem); } }
private void cmdSQLinserterIND_Click(object sender, EventArgs e) { string sConn = string.Format("DataSource={0}", cDB_Settings.CE_ConnectionString); System.Data.SqlServerCe.SqlCeConnection myConnection = new System.Data.SqlServerCe.SqlCeConnection(sConn); try { myConnection.Open(); try { SqlCeCommand myCommand = new SqlCeCommand("INSERT INTO SMT_TEST (Test_Datum,Test_Text, Test_Nummer) " + "Values (" + cDB_SQL_CE.DATE_TIME_TO_DB(DateTime.Now) + ",'" + addTimestamp("Test") + "'," + addTimestamp("123.45") + ")", myConnection); tbSQLergebnisbox.Text = cDB_SQL_CE.DATE_TIME_TO_DB(DateTime.Now) + "," + addTimestamp("Test") + "," + addTimestamp("123.45"); myCommand.ExecuteNonQuery(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { if (myConnection.State != ConnectionState.Closed) { myConnection.Close(); myConnection = null; } } }
} //ExecuteUppdate //_______________________________________________________________________________________________________________ // executer la requete select sans ouvrir la connexion internal static DataSet ExecuteSelectN(string requête, SqlCeConnection connexion) { connexion = Connexion.getInstance().OpenConnection(); //using (connexion = Connexion.getInstance().OpenConnection()) //{ try { SqlCeCommand cmd = connexion.CreateCommand(); cmd.CommandText = requête; SqlCeDataAdapter da = new SqlCeDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); return(ds); } catch (Exception ex) { FileInfo fi = new FileInfo(Program.pathExe + "\\log.txt"); using (StreamWriter sw = fi.AppendText()) { sw.WriteLine(DateTime.Now + "/ " + ex.Message + " / " + requête + " / Classe Requete M.ExecuteSelectN \r\n"); sw.Close(); } //MessageBox.Show(a.ToString()); return(null); } finally { // Connexion.getInstance().closeConnection(); } //} }
/// <summary> /// 默认构造函数 /// </summary> public ConnLocalDB() { string connStr; connStr = System.Configuration.ConfigurationManager.AppSettings["connStr"].ToString(); connectionString = connStr; Connection = new SqlCeConnection(connectionString); }
//Returns Open IDbconnection public IDbConnection Connection() { //This is where we provide a SqlCe implementation of System.Data.IDbConnection var vConnection = new System.Data.SqlServerCe.SqlCeConnection(); vConnection.Open(); return(vConnection); }
//@Brief Constructor de la clase. Inicializa la conexión SQL //@Param[in] SQLCeDB Archivo de base de datos //@Param[in] SQLCeParams Parámetros adicionales de conexión public SQLCompactConnection(string SQLCeDB, string SQLCeParams = "") { m_sqlDB = SQLCeDB; m_sqlConnectionString = "Data Source='" + SQLCeDB + "'"; if (SQLCeParams != "") { m_sqlConnectionString = m_sqlConnectionString + ";" + SQLCeParams; } m_sqlConnection = new SqlCeConnection(m_sqlConnectionString); }
private void DataBind() { string connString = @"Data Source=E:\微信\WeChat Files\wxid_g4badj1jvdlg21\FileStorage\File\2019-12\Payroll\Payroll\Database1.sdf"; SqlCeConnection connection = new System.Data.SqlServerCe.SqlCeConnection(connString); connection.Open(); string sqlStr = " select * from payemployee"; SqlCeCommand cmd = new SqlCeCommand(sqlStr, connection); dapt = new SqlCeDataAdapter(cmd); ds = new DataSet(); dapt.Fill(ds); this.dataGridView1.DataSource = ds.Tables[0]; }
private void button1_Click(object sender, System.EventArgs e) { cn = new System.Data.SqlServerCe.SqlCeConnection("Data Source=\\My Documents\\prac3.sdf"); cn.Open(); SqlCeCommand cmd = cn.CreateCommand(); cmd.CommandText = "SELECT TitleName FROM Titles"; SqlCeDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { MessageBox.Show(reader.GetString(0)); } }
private void button3_Click(object sender, EventArgs e) //Loading a new wordlist { OpenFileDialog loadlist = new OpenFileDialog(); loadlist.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*"; loadlist.FilterIndex = 1; loadlist.Multiselect = false; loadlist.InitialDirectory = ""; if (loadlist.ShowDialog() == DialogResult.OK) //user clicked ok { String Filepath = loadlist.FileName; System.IO.StreamReader inpfile = new System.IO.StreamReader(Filepath); System.Data.SqlServerCe.SqlCeConnection con = new System.Data.SqlServerCe.SqlCeConnection(); System.Data.SqlServerCe.SqlCeDataAdapter daHangmanDB; DataRow drow; DataSet dsWordlist = new DataSet(); con.ConnectionString = "Data Source=HangmanDB.sdf"; con.Open(); SqlCeCommand cmd = con.CreateCommand(); cmd.CommandText = "DELETE FROM Wordlist"; cmd.ExecuteNonQuery(); daHangmanDB = new System.Data.SqlServerCe.SqlCeDataAdapter("SELECT * From Wordlist", con); daHangmanDB.Fill(dsWordlist, "Wordlist"); con.Close(); String data, category, words; while ((data = inpfile.ReadLine()) != null) { category = data.Split(',')[0]; words = data.Split(',')[1]; drow = dsWordlist.Tables["Wordlist"].NewRow(); drow[1] = category; drow[2] = words; dsWordlist.Tables["Wordlist"].Rows.Add(drow); } con.Open(); System.Data.SqlServerCe.SqlCeCommandBuilder cb; cb = new System.Data.SqlServerCe.SqlCeCommandBuilder(daHangmanDB); cb.DataAdapter.Update(dsWordlist.Tables["Wordlist"]); con.Close(); MessageBox.Show("Database Updated."); } }
private void button2_Click(object sender, EventArgs e) //delete { System.Data.SqlServerCe.SqlCeConnection con = new System.Data.SqlServerCe.SqlCeConnection(); System.Data.SqlServerCe.SqlCeDataAdapter daHangmanDB; DataRow drow; DataSet dsSavedGame_Words = new DataSet(); con.ConnectionString = "Data Source=HangmanDB.sdf"; con.Open(); daHangmanDB = new System.Data.SqlServerCe.SqlCeDataAdapter("SELECT * From SavedGame_Words", con); daHangmanDB.Fill(dsSavedGame_Words, "SavedGame_Words"); con.Close(); int selectedID = System.Convert.ToInt32(listView1.SelectedItems[0].SubItems[0].Text); for (int i = 0; i < dsSavedGame_Words.Tables["SavedGame_Words"].Rows.Count; ++i) { drow = dsSavedGame_Words.Tables["SavedGame_Words"].Rows[i]; if (System.Convert.ToInt32(drow[0]) == selectedID) { dsSavedGame_Words.Tables["SavedGame_Words"].Rows[i].Delete(); //Marks row for deletion (does not remove) } } con.Open(); SqlCeCommand cmd = con.CreateCommand(); cmd.CommandText = "DELETE FROM SavedGame_Words"; cmd.ExecuteNonQuery(); con.Close(); con.Open(); System.Data.SqlServerCe.SqlCeCommandBuilder cb; cb = new System.Data.SqlServerCe.SqlCeCommandBuilder(daHangmanDB); cb.DataAdapter.Update(dsSavedGame_Words.Tables["SavedGame_Words"]); con.Close(); MessageBox.Show("Database Updated."); con.Close(); con.Open(); cmd = con.CreateCommand(); cmd.CommandText = "DELETE FROM SavedGames WHERE ID=" + System.Convert.ToString(selectedID); cmd.ExecuteNonQuery(); con.Close(); listView1.Items.Remove(listView1.SelectedItems[0]); }
public bool Connect() { try { //conn = new System.Data.SqlServerCe.SqlCeConnection(@"Data Source=|DataDirectory|\Database.sdf"); conn = new System.Data.SqlServerCe.SqlCeConnection(@"Data Source=" + path + @"\Database.sdf"); conn.Open(); return true; } catch (System.Data.SqlServerCe.SqlCeException e) { conn = null; return false; } }
private SqlCeConnection CrearSDF(Empresa empresa) { SqlCeEngine DBDatabase = null; try { if (!System.IO.File.Exists(string.Format("{0}BD\\terminal.sdf", path))) { RadNotification1.Text = String.Format("<b>{0}</b><br/>{1}", (string)GetGlobalResourceObject("ResourceLainsaSci", "Warning"), (string)GetGlobalResourceObject("ResourceLainsaSci", "ExportFile")); RadNotification1.Show(); return(null); } System.IO.FileInfo file = new System.IO.FileInfo(string.Format("{0}BDII\\{1}_{2}.sdf", path, empresa.EmpresaId.ToString(), DateTime.Now.ToShortDateString()).Replace("/", "_")); System.IO.File.Copy(string.Format("{0}BD\\terminal.sdf", path), file.FullName, true); archivo = file.Name; string conn = string.Format("Data Source={0};Password =;Persist Security Info=True", file); DBDatabase = new SqlCeEngine(conn); SqlCeConnection vCon = new System.Data.SqlServerCe.SqlCeConnection(conn); //SqlCeCommand VComandoSQL = new System.Data.SqlServerCe.SqlCeCommand("", vCon); //*** Creo la Base de Datos //DBDatabase.CreateDatabase(); //DBDatabase.Dispose(); vCon.Open(); return(vCon); } catch (Exception VError) { throw VError; } finally { // vCon.Close(); // vCon.Dispose(); // vCon = null; if (DBDatabase != null) { DBDatabase.Dispose(); } } }
private void button2_Click(object sender, System.EventArgs e) { cn = new System.Data.SqlServerCe.SqlCeConnection("Data Source=\\My Documents\\prac3.sdf"); SqlCeCommand cmd = new SqlCeCommand("SELECT * FROM Titles", cn); cmd.CommandType = CommandType.Text; SqlCeDataAdapter adapter = new SqlCeDataAdapter(); adapter.SelectCommand = cmd; DataSet ds = new DataSet(); adapter.Fill(ds, "Titles"); //foreach(DataRow dr in ds.Tables["Titles"].Rows) //{ // MessageBox.Show(dr["TitleName"].ToString()); //} this.dataGrid1.DataSource = ds.Tables["Titles"]; }
private void Form1_Load(object sender, System.EventArgs e) { try { System.IO.File.Delete("\\My Documents\\prac3.sdf"); System.Data.SqlServerCe.SqlCeEngine SQLEngine = new System.Data.SqlServerCe.SqlCeEngine("data source=\\My Documents\\prac3.sdf"); SQLEngine.CreateDatabase(); // Next, open the database. cn = new System.Data.SqlServerCe.SqlCeConnection("Data Source=\\My Documents\\prac3.sdf"); cn.Open(); //Create the structure of the database using SQL statements. // Create the Titles table. String SQL = "CREATE TABLE Titles (TitleID nchar(5) Primary Key " + "NOT NULL,TitleName nvarchar(40) NOT NULL)"; System.Data.SqlServerCe.SqlCeCommand cmd = new System.Data.SqlServerCe.SqlCeCommand(SQL, cn); cmd.CommandType = CommandType.Text; cmd.ExecuteNonQuery(); SQL = ""; //Insert Data into the table. SQL = "INSERT INTO Titles (TitleID, TitleName) VALUES " + "('MSCF1','Compact Framework')"; cmd.CommandText = SQL; cmd.ExecuteNonQuery(); SQL = ""; SQL = "INSERT INTO Titles (TitleID, TitleName) VALUES " + "('MSCE1','SQLCE DB')"; cmd.CommandText = SQL; cmd.ExecuteNonQuery(); } catch (SqlCeException ex) { ShowErrors(ex); } finally { cn.Close(); } }
public static List <PDODictionaryEntry> GetDictionary(String DatabaseName, EthCATDevice slave) { string connectionString = "Data Source=" + DatabaseName; System.Data.SqlServerCe.SqlCeConnection con = new System.Data.SqlServerCe.SqlCeConnection(connectionString); try { con.Open(); int databaseid = DeviceDescrProvider.GetSlaveDatabaseId(con, slave._ManufacturerId, slave._TypeId, slave.Revision); if (databaseid == -1) { return(null); } List <PDODictionaryEntry> ret = new List <PDODictionaryEntry>(); string command = "SELECT * FROM PDO_Dictionary WHERE SlaveId=" + databaseid.ToString(); SqlCeCommand cmd = new SqlCeCommand(command, con); SqlCeDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { string FinalType = GetFinalType(con, databaseid, (string)reader[4]); // At this level RW is unknow (not in the XML file) PDODictionaryEntry e = new PDODictionaryEntry(Convert.ToInt32(reader[1]), Convert.ToUInt32(reader[2]), (string)reader[3], FinalType, PDOAccessLevel.Unknow); ret.Add(e); e.AddSubIndexData(con, databaseid); } con.Close(); return(ret); } catch { Trace.WriteLine("Database content Error"); } return(null); }
private void cmdSQLreaderIND_Click(object sender, EventArgs e) { string sConn = string.Format("DataSource={0}", cDB_Settings.CE_ConnectionString); System.Data.SqlServerCe.SqlCeConnection myConnection = new System.Data.SqlServerCe.SqlCeConnection(sConn); try { myConnection.Open(); try { SqlCeDataReader myReader = null; SqlCeCommand myCommand = new SqlCeCommand("select TOP(1) Test_Text from SMT_Test order by aic_SMT_TEST DESC", myConnection); myReader = myCommand.ExecuteReader(); while (myReader.Read()) { tbSQLergebnisbox.Text = myReader["Test_Text"].ToString(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { if (myConnection.State != ConnectionState.Closed) { myConnection.Close(); myConnection = null; } } }
public Conexao() { ConfiguraStringConexao(); _Conexao = new System.Data.SqlServerCe.SqlCeConnection(_StrConexao); }
public EntitiesDatabaseModel(string tableName) { this.TableName = tableName; _connection = new SqlCeConnection(DatabaseInfo.connectionString); }
public EntitiesDatabaseModel() { _connection = new SqlCeConnection(DatabaseInfo.connectionString); }
// Сформировать private void button1_Click(object sender, EventArgs e) { XmlTextReader reader = new XmlTextReader("http://test-danru.rhcloud.com/data.xml"); TAG id = 0; // идентификатор тегов int PK = 0; // номер записи ArrayList tuple = new ArrayList(); // таблица statistics TUPLE temp = new TUPLE(); // строка таблицы // создание таблицы в памяти while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: // открывающий тег switch (reader.Name) { case "Item": // <Item Date> if (reader.AttributeCount != 0) temp.Date = "'" + DateTime.ParseExact(reader.GetAttribute(0), "dd.MM.yyyy", CultureInfo.InvariantCulture).ToString("yyyyMMdd") + "'"; break; case "Views": id = TAG.Views; break; case "Clicks": id = TAG.Clicks; break; } break; case XmlNodeType.Text: // содержимое switch (id) { case TAG.Views: temp.Views = reader.Value; id = 0; break; case TAG.Clicks: temp.Clicks = reader.Value; id = 0; temp.ID = ++PK; tuple.Add(new TUPLE(temp.ID, temp.Date, temp.Views, temp.Clicks)); break; } break; } } // --------------------------------------------------------------------------------------------- // для создания новой БД if (File.Exists("advertisement-statistics.sdf")) File.Delete("advertisement-statistics.sdf"); // создание файла БД SqlCeEngine engine = new SqlCeEngine("Data Source='advertisement-statistics.sdf'; LCID=1033;"); engine.CreateDatabase(); engine.Dispose(); // соединение с файлом БД var connection = new System.Data.SqlServerCe.SqlCeConnection(); connection.ConnectionString = "Data Source='advertisement-statistics.sdf'"; connection.Open(); // создание БД var command = new System.Data.SqlServerCe.SqlCeCommand(); command.Connection = connection; command.CommandText = "CREATE TABLE data (" + "ID int," + "Date datetime NOT NULL," + "Views int NOT NULL," + "Clicks int NOT NULL," + "PRIMARY KEY (ID) );"; command.ExecuteReader(); // заполнение БД foreach (TUPLE a in tuple) { command.CommandText = "INSERT INTO [data] VALUES (" + a.ID + ", " + a.Date + ", " + a.Views + ", " + a.Clicks + ")"; command.ExecuteReader(); } listView1.Items.Clear(); // отображение БД command.CommandText = "SELECT * FROM [data]"; var table = command.ExecuteReader(); int i; int fieldCount = table.FieldCount; while (table.Read() == true) { i = 0; lvi = new ListViewItem(); lvi.Text = table.GetValue(i++).ToString(); listView1.Items.Add(lvi); for (; i < fieldCount; ++i) lvi.SubItems.Add(table.GetValue(i).ToString()); } // среднее количество просмотров и кликов command.CommandText = "SELECT AVG(Views), AVG(Clicks) FROM [data]"; table = command.ExecuteReader(); listView1.Items.Add(new ListViewItem()); // пустая строка while (table.Read() == true) { lvi = new ListViewItem(); listView1.Items.Add(lvi); lvi.SubItems.Add(""); lvi.SubItems.Add("AVG = " + table.GetValue(0).ToString()); lvi.SubItems.Add("AVG = " + table.GetValue(1).ToString()); } // общее количество просмотров и кликов command.CommandText = "SELECT SUM(Views), SUM(Clicks) FROM [data]"; table = command.ExecuteReader(); while (table.Read() == true) { lvi = new ListViewItem(); listView1.Items.Add(lvi); lvi.SubItems.Add(""); lvi.SubItems.Add("SUM = " + table.GetValue(0).ToString()); lvi.SubItems.Add("SUM = " + table.GetValue(1).ToString()); } // данные за последние 5 дней command.CommandText = "SELECT TOP 5 * FROM [data] ORDER BY Date DESC"; table = command.ExecuteReader(System.Data.CommandBehavior.CloseConnection); listView1.Items.Add(new ListViewItem()); // пустая строка lvi = new ListViewItem(); // строка listView1.Items.Add(lvi); lvi.SubItems.Add("----- Данные за последние 5 дней -----"); while (table.Read() == true) { i = 0; lvi = new ListViewItem(); lvi.Text = table.GetValue(i++).ToString(); listView1.Items.Add(lvi); for (; i < fieldCount; ++i) lvi.SubItems.Add(table.GetValue(i).ToString()); } table.Close(); connection.Close(); }
/// <summary> /// Read the values from database and returns ClassList /// </summary> /// <returns></returns> protected System.Collections.Generic.List <ClassList> ReadFromDatabase(int SelectType) { System.Collections.Generic.List <ClassList> lstClass = new System.Collections.Generic.List <ClassList>(); string strCon = @"Data Source=..\..\..\..\..\..\..\Common\Data\Diagram\db\Diagram.sdf"; System.Data.SqlServerCe.SqlCeConnection connection = new System.Data.SqlServerCe.SqlCeConnection(strCon); connection.Open(); System.Data.SqlServerCe.SqlCeDataAdapter adapter; SqlCeCommand comm; if (SelectType == 1) { comm = new SqlCeCommand("Select * from tblClassDiagram", connection); } else { comm = new SqlCeCommand("Select * from tblClassDiagram1 order by ClassId", connection); } adapter = new System.Data.SqlServerCe.SqlCeDataAdapter(comm); System.Data.DataSet ds = new System.Data.DataSet("Table"); adapter.Fill(ds); if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { DataTable dt = new DataTable(); dt = ds.Tables[0]; for (int i = 0; i < dt.Rows.Count; i++) { ClassList classObj = new ClassList(); classObj.ClassName = dt.Rows[i]["ClassName"].ToString(); classObj.ClassType = dt.Rows[i]["ClassType"].ToString(); classObj.ObjectType = dt.Rows[i]["ObjectType"].ToString(); for (int j = i; j < dt.Rows.Count; j++) { if (dt.Rows[i]["ClassName"].ToString() == dt.Rows[j]["ClassName"].ToString()) { if (!string.IsNullOrEmpty(dt.Rows[j]["Properties"].ToString())) { PropertyList propertyList = new PropertyList(); propertyList.PropertyName = dt.Rows[j]["Properties"].ToString(); propertyList.PropertyType = (PropertyType)(Enum.Parse(typeof(PropertyType), dt.Rows[j]["PropertyType"].ToString())); classObj.PropertyList.Add(propertyList); } if (!string.IsNullOrEmpty(dt.Rows[j]["Methods"].ToString())) { MethodList methodList = new MethodList(); methodList.MethodName = dt.Rows[j]["Methods"].ToString(); methodList.MethodType = (MethodType)(Enum.Parse(typeof(MethodType), dt.Rows[j]["MethodType"].ToString())); classObj.MethodList.Add(methodList); } } else { i = j - 1; lstClass.Add(classObj); break; } if (j == dt.Rows.Count - 1) { i = j; lstClass.Add(classObj); break; } } } } return(lstClass); }
public RegionsDatabaseModel() { _connection = new SqlCeConnection(DatabaseInfo.connectionString); }
/// <summary> /// 带参数的构造函数 /// </summary> /// <param name="newConnectionString"> 数据库联接字符串 </param> /// <example> /// <code language="C#" title="init ConnLocalDB"> /// #region interact with local database via SQL Script /// RF.GlobalClass.DB.ConnLocalDB cldb = new RF.GlobalClass.DB.ConnLocalDB(global::WindowsFormsApplication4sdtapi.Properties.Settings.Default.ClientScenicTicketSaleSystemConnectionString + @"Password=""7654321"";"); /// DataSet ds = cldb.ReturnDataSet( /// @"INSERT INTO [Order] /// ([D_ORDER_ID] /// ,[PRO_ID] /// ,[SALE_PRICE] /// ,[SALE_UNIT_PRICE] /// ,[STATUS] /// ,[TICKET_COUNT] /// ,[USE_TIME]) /// VALUES /// (N'" + order.id + @"' /// ,N'" + order.product.id + @"' /// ," + order.amount + @" /// ," + order.product.price + @" /// ,N'" + order.status + @"' /// ," + order.ticketCount + @" /// ,N'" + order.visitDate + @"' /// );" /// ); /// ds = cldb.ReturnDataSet(@" /// SELECT ID FROM [Order] /// WHERE [D_ORDER_ID] = N'" + order.id + @"' /// AND [USE_TIME] = N'" + order.visitDate + @"' /// " /// ); /// String OrderInnerID = ""; /// if (ds.Tables.Count > 0) /// { /// OrderInnerID = Convert.ToString(ds.Tables[0].Rows[0][0]); /// } /// </code> /// </example> public ConnLocalDB(string newConnectionString) { connectionString = newConnectionString; Connection = new SqlCeConnection(connectionString); }
private void button3_Click(object sender, EventArgs e) { con = new System.Data.SqlServerCe.SqlCeConnection(); con.ConnectionString = "DataSource=|DataDirectory|cidb13.sdf"; SqlCeCommand cmd2 = con.CreateCommand(); cmd2.CommandText = "SELECT * From Employee_reg "; int flag = 0, f1 = 0; con.Open(); cmd2.ExecuteNonQuery(); SqlCeDataReader readData = cmd2.ExecuteReader(); if (readData != null) { while (readData.Read()) { if (readData.GetString(8) == "Reviewed") { if (readData.GetString(2) == textBox2.Text && (readData.GetString(1) == textBox1.Text)) { /* if (textBox1.Text == "Admin") * { * string u1 = readData.GetString(0); * this.Hide(); * adminPanel ad = new adminPanel(); * LoginInfo.UserID = u1; * ad.Show(); * flag=1; * * } * else*/ string u = readData.GetString(0); this.Hide(); User_DashBoard er = new User_DashBoard(); LoginInfo.UserID = u; er.Show(); flag = 1; } } else if (readData.GetString(8).Equals("Not Reviewed")) { if (readData.GetString(2) == textBox2.Text && (readData.GetString(1) == textBox1.Text)) { f1 = 1; flag = 1; } } } } if (flag == 0) { MessageBox.Show("Wrong password or username.Try again "); } else if (f1 == 1) { MessageBox.Show("Login Verfication in process.\nCan't access.\nContact Admin for Login Details"); } //ds1 = new DataSet(); //string sql = "SELECT * From Employee_reg where UserName='******'"; //da = new System.Data.SqlServerCe.SqlCeDataAdapter(sql, con); //da.Fill(ds1, "Employee_reg"); //DataRow drow = ds1.Tables["Employee_reg"].Rows[0]; /*foreach (DataRow drow in ds1.Employee_reg) * { * if (drow.ItemArray[0].Equals(textBox1.Text) && drow.ItemArray[1].Equals(textBox2.Text)) * { * this.Hide(); * User_DashBoard er = new User_DashBoard(); * er.str1 = drow.ItemArray.GetValue(1).ToString(); * er.Show(); * } * else * { * MessageBox.Show("Wrong password or username.Try again "); * } * }*/ con.Close(); }
// Entry point to parse the XML file public static string AddDeviceDescr(String DataBase, String XMLFilename) { if (!File.Exists(DataBase)) { return("Error : No database file !"); } string connectionString = "Data Source=" + DataBase; System.Data.SqlServerCe.SqlCeConnection con = new System.Data.SqlServerCe.SqlCeConnection(connectionString); // http://www.codeproject.com/Articles/21208/Store-or-Save-images-in-SQL-Server try { con.Open(); XmlDocument doc = new XmlDocument(); doc.Load(XMLFilename); // first Get vendor & slave Id XmlNode node = doc.SelectSingleNode("/EtherCATInfo/Vendor/Id"); uint VendorId = String_2_Uint(node.InnerText); node = doc.SelectSingleNode("/EtherCATInfo/Descriptions/Devices/Device/Type"); string device_name = node.InnerText; XmlAttribute at = node.Attributes["ProductCode"]; uint ProductCode = String_2_Uint(at.Value); at = node.Attributes["RevisionNo"]; uint ProductRev = String_2_Uint(at.Value); if (GetSlaveDatabaseId(con, VendorId, ProductCode, ProductRev) != -1) { con.Close(); return("Slave Device already into the database"); } int SlavePrimaryKey = GetPrimaryKeyValue(con, "SLAVES", "Id"); string command = @"INSERT INTO SLAVES (Id, VendorId, DeviceId, Rev, Name) VALUES(" + SlavePrimaryKey.ToString() + "," + VendorId.ToString() + "," + ProductCode.ToString() + "," + ProductRev.ToString() + ",'" + device_name + "');"; SqlCeCommand cmd = new SqlCeCommand(command, con); cmd.ExecuteNonQuery(); XmlNodeList nodes = doc.DocumentElement.SelectNodes("/EtherCATInfo/Descriptions/Devices/Device/Profile/Dictionary/Objects/Object"); // Get all Index, it's simple foreach (XmlNode node2 in nodes) { XmlNode n = node2.SelectSingleNode("Index"); uint Idx = String_2_Uint(n.InnerText); n = node2.SelectSingleNode("Name"); string Name = n.InnerText; n = node2.SelectSingleNode("Type"); string type = n.InnerText; n = node2.SelectSingleNode("BitSize"); uint Bitsize = String_2_Uint(n.InnerText); command = "INSERT INTO PDO_Dictionary VALUES(" + SlavePrimaryKey.ToString() + "," + Idx.ToString() + "," + Bitsize.ToString() + ",'" + Name + "','" + type + "')"; cmd = new SqlCeCommand(command, con); cmd.ExecuteNonQuery(); } // Get all Datatype : SubIndex, more complex to do (multiple options) AddDeviceDataType(con, doc, SlavePrimaryKey); con.Close(); } catch { return("Error with XML File, or Database"); } return("Done"); }