Added DataColumns not being saving in Access Database - datatable

I would like to write code to add a DataColumn to a DataTable, but when I save the DataTable, it does not include the new DataColumn.
It saves any new DataRows I add, but not the DataColumns.
Can somebody please tell me what I am doing wrong?
public partial class Form1 : Form
{
MyDatabase DB;
DataTable Products;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DB = new MyDatabase();
DB.Open(#"C:\Users\Grant\Documents\Database.accdb");
Products = DB.GetTable("Products");
AddColumn();
AddRow();
DB.Save(Products);
}
private void AddColumn()
{
DataColumn Column = new DataColumn();
Column.DataType = Type.GetType("System.String");
Column.ColumnName = "TestColumn";
Products.Columns.Add(Column);
}
private void AddRow()
{
DataRow Row;
Row = Products.Rows.Add(1, "B", "C");
}
}
class MyDatabase
{
// The following program has to be installed on the computer
// http://www.microsoft.com/downloads/en/details.aspx?familyid=7554F536-8C28-4598-9B72-EF94E038C891&displaylang=en
private String provider = "Microsoft.ACE.OLEDB.12.0";
private String source;
private OleDbConnection connection;
private String connectionString;
private DataSet dataSet = new DataSet();
private OleDbDataAdapter adapter;
private OleDbCommandBuilder commandBuilder;
public String Provider
{
get { return provider; }
set { provider = value; }
}
public String Source
{
get { return Source; }
set { source = value; }
}
public void Open(String Filename)
{
connectionString = #"Provider=" + provider + #";Data Source=" + Filename;
connection = new OleDbConnection(connectionString);
connection.Open();
adapter = new OleDbDataAdapter();
}
public void BuildStrings()
{
commandBuilder = new OleDbCommandBuilder(adapter);
adapter.UpdateCommand = commandBuilder.GetUpdateCommand();
adapter.InsertCommand = commandBuilder.GetInsertCommand();
adapter.DeleteCommand = commandBuilder.GetDeleteCommand();
}
public DataTable GetTable(String TableName)
{
adapter.SelectCommand = new OleDbCommand("SELECT * From " + TableName, connection);
BuildStrings();
adapter.Fill(dataSet, TableName);
return dataSet.Tables[TableName];
}
public void Save(DataTable Table)
{
adapter.Update(Table);
adapter.Update(dataSet, "Products");
}
}

Got an answer from a different forum.
You can not add new column/field to database table using dataset or datatable you might need to use "ALTER TABLE" with ADO.NET commands. Check below links
How Can I Insert New Column Into A Database Table Using SqlDataAdapter and DataTable?[^]
adding a column to a SQL table in VB using ADO.NET commands[^]

Related

spring boot with thymeleaf html table with class model array

I got this class model (I made it only 2 column),
public class DataModel {
private int id;
private String name;
public DataModel() {}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
Here's the data.json,
[
{
"id":1,
"name":"Bill",
},
{
"id":2,
"name":"Steve",
}
]
Here's the controller class on the #PostConstruct(take 2-3 hours for figuring out the can't resolve json),
#PostConstruct
private void loadData() {
// load json
String strJson = null;
ClassPathResource classPathResource = new ClassPathResource("json/data.json");
try {
byte[] binaryData = FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
strJson = new String(binaryData, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
// setup array mapper
ObjectMapper objectMapper = new ObjectMapper();
DataModel[] datawiz;
try {
datawiz = objectMapper.readValue(strJson, DataModel[].class);
// this print the first array on the json
System.out.println("Id = " + datawiz[0].getId() + " & Name = " + datawiz[0].getName());
} catch (Exception e) {
e.printStackTrace();
}
There's no problem there.
How do I use it in thymeleaf html?
I got only example like this,
// create menu list
DataModel menulist1 = new DataModel(1, "Bill");
DataModel menulist2 = new DataModel(2, "Steve");
// create the list
theData = new ArrayList<>();
add to the list
theData.add(menulist1);
theData.add(menulist2);
#GetMapping("/list")
public String listMenu(Model theModel) {
// add to the spring model
theModel.addAttribute("thelist", theData);
return "menu-list";
I can't do this theData=datawiz (of course removing those example with menulist* and .add).
Then on the menu-list.html,
<table>
<tbody>
<tr th:each="theList : ${thelist}">
<td th:text="${theList.id}" />
<td th:text="${theList.name}" />
</tr>
</tbody>
</table>
Tried this,
for(DataModel dataw : datawiz[]) {
theData.add(dataw);
}
didn't work.
I was thinking to use simple "for" like in phyton (I'm a previous snake coder) but the old tricks did it,
for(int i = 0; i < datawiz.length; i++) {
DataModel dat = new DataModel(datawiz[i].getId(),datawiz[i].getName());
theDatawiz.add(dat);
}

Database handler globally as Singleton pattern in xamarin forms

I am developing an application which have a local database for offline support. So I am using Sqlite.net.pcl plugin and its working fine for all Create, Insert, Update and Delete table for every class model.
But instead of creating a separate database activities like insert, get, update for each Model class, I tried to worked on singeton pattern of common database handler(DatabasHandler.cs).
This is my code which I tried to workout singleton pattern,
public void CreateTable<T>() where T : new()
{
var myClass = new T();
myDatabase.CreateTableAsync<T>().Wait();
}
I called this function from my EmployeeViewModel class like this;
App.Database.CreateTable<EmployeeModel>();
here EmployeeModel is a model class and its worked fine, also the above function is successfully created a Employee Table. Doing the same way I created rest of the Tables from each ViewModel like this;
App.Database.CreateTable<SalaryModel>(); // call from SalaryViewModel Page
App.Database.CreateTable<EmployeeAttendanceModel>(); // call from AttendanceViewModel Page
Next: So how can I insert and get all list items into DatabaseHandler.cs using same (Create Table)singleton pattern. My question is;
How should I create a method for Insert/Get/Update a list in DatabaseHandler.cs(Singleton class)?
How should I call those method(Insert/Get/Update) from its viewmodel?
Please help me,
Now I had a similar thing in my Old XF app this is how I implemented the Singleton this will also answer your first question:
How should I create a method for Insert/Get/Update a list in DatabaseHandler.cs(Singleton class)?
public class DatabaseHandler: IDisposable
{
private SQLiteConnection conn;
//public static string sqlpath;
private bool disposed = false;
private static readonly Lazy<DatabaseHandler> database = new Lazy<DatabaseHandler>(() => new DatabaseHandler());
private DatabaseHandler() { }
public static DatabaseHandler Database
{
get
{
return database.Value;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
Dispose();
}
disposed = true;
}
public bool InitDatabase()
{
var ifExist = true;
try
{
this.CreateDatabase();
ifExist = TableExists(nameof(LocationModel), conn);
if (!ifExist)
this.CreateTable<LocationModel>();
return true;
}
catch (Exception ex)
{
return false;
}
}
public static bool TableExists(String tableName, SQLiteConnection connection)
{
var cmd = connection.CreateCommand("SELECT name FROM sqlite_master WHERE type = 'table' AND name = #name", new object[] { tableName });
//cmd.CommandText = "SELECT * FROM sqlite_master WHERE type = 'table' AND name = #name";
//cmd.Parameters.Add("#name", DbType.String).Value = tableName;
string tabledata = cmd.ExecuteScalar<string>();
return (cmd.ExecuteScalar<string>() != null);
}
public SQLiteConnection GetConnection()
{
var sqliteFilename = "xamdblocal.db3";
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); // Documents folder
var path = Path.Combine(documentsPath, sqliteFilename);
Console.WriteLine(path);
if (!File.Exists(path)) File.Create(path);
//var plat = new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid();
var conn = new SQLiteConnection(path);
// Return the database connection
return conn;
}
private bool CreateDatabase()
{
conn = GetConnection();
string str = conn.DatabasePath;
return true;
}
public bool CreateTable<T>()
where T : new()
{
conn.DropTable<T>();
conn.CreateTable<T>();
return true;
}
public bool InsertIntoTable<T>(T LoginData)
where T : new()
{
conn.Insert(LoginData);
return true;
}
public bool InsertBulkIntoTable<T>(IList<T> LoginData)
where T : class //new()
{
conn.InsertAll(LoginData);
return true;
}
public List<T> SelectDataFromTable<T>()
where T : new()
{
try
{
return conn.Table<T>().ToList();
}
catch (Exception ex)
{
return null;
}
}
public List<T> SelectTableDatafromQuery<T>(string query)
where T : new()
{
return conn.Query<T>(query, new object[] { })
.ToList();
}
public bool UpdateTableData<T>(string query)
where T : new()
{
conn.Query<T>(query);
return true;
}
public void UpdateTableData<T>(IEnumerable<T> query)
where T : new()
{
conn.UpdateAll(query);
}
public void UpdateTableData<T>(T query)
where T : new()
{
conn.Update(query);
}
public bool DeleteTableData<T>(T LoginData)
{
conn.Delete(LoginData);
return true;
}
public bool DeleteTableDataFromPrimaryKey<T>(object primaryKey)
{
conn.Delete(primaryKey);
return true;
}
public bool DeleteTableDataFromQuery<T>(string query)
where T : new()
{
conn.Query<T>(query);
return true;
}
}
How should I call those method(Insert/Get/Update) from its viewmodel? Please help me,
Now for Eg: you want to insert location's Lat Long in your local database where your local model looks something like this:
public class LocationModel
{
[AutoIncrement, PrimaryKey]
public int Id { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public string Address { get; set; }
}
So first what you will do is create an instance of LocationModel something like this:
var locationModel = new LocationModel
{
Latitude = location.Latitude,
Longitude = location.Longitude
};
Then insert it something like this:
DatabaseHandler.Database.InsertIntoTable<LocationModel>(locationModel);
Also, do not forget to add the SQLiteNetExtensions in your project for Linq support.
Goodluck feel free to revert in case of queries

How to refresh tableview after adding the new data in JavaFx

I am currently working on JAVA FX application to fetch the user's information from JIRA REST API. I want to have a refresh button and on clicking it,the table view must be shown with the newly added data.
Please have a look at the code.
My POJO class
public class Issues {
private String jiraKey;
private String jiraSummary;
private String jiraPriority;
private String jiraAssignee;
private String jiraIssueType;
private Hyperlink hyperLink;
private String loghours;
private String commentLogHours;
public Issues(String jiraKey, String jiraSummary, String jiraPriority, String jiraAssignee, String jiraIssueType) {
super();
this.hyperLink = new Hyperlink(jiraKey);
this.jiraSummary = jiraSummary;
this.jiraPriority = jiraPriority;
this.jiraAssignee = jiraAssignee;
this.jiraIssueType = jiraIssueType;
this.hyperLink = hyperLink;
this.loghours = loghours;
this.commentLogHours = commentLogHours;
}
public String getJiraKey() {
return jiraKey;
}
public void setJiraKey(String jiraKey) {
this.jiraKey = jiraKey;
}
//getters and setters
}
My Observable list method which populates the data to table
Class ABC{
public ObservableList<Issues> issueJsonList(){
// A processed arraylist
ObservableList<Issues> data = FXCollections.observableList(list);
return data;
}
}
Here's my tableview code.
#SuppressWarnings({ "unchecked", "rawtypes" })
public TableView<Issues> initTable() throws IOException, URISyntaxException {
TableView<Issues> table = new TableView<Issues>();
table.setEditable(true);
TableColumn<Issues, Hyperlink> jiraKey = new TableColumn<>(keyField);
jiraKey.setCellValueFactory(new PropertyValueFactory("hyperLink"));
jiraKey.setCellFactory(new HyperlinkCell());
TableColumn jiraPriority = new TableColumn(priorityField);
TableColumn jiraIssueType = new TableColumn(issueTypeField);
TableColumn jiraSummary = new TableColumn(summaryField);
TableColumn jiraAssignee = new TableColumn(assigneeField);
TableColumn workLogCol = new TableColumn(workLogField);
TableColumn timeSpent = new TableColumn(timeSpentField);
TableColumn commentTimeLog = new TableColumn(commentField);
workLogCol.getColumns().addAll(timeSpent, commentTimeLog);
jiraSummary.setCellValueFactory(new PropertyValueFactory("jiraSummary"));
jiraIssueType.setCellValueFactory(new PropertyValueFactory("jiraIssueType"));
jiraPriority.setCellValueFactory(new PropertyValueFactory("jiraPriority"));
jiraAssignee.setCellValueFactory(new PropertyValueFactory("jiraAssignee"));
timeSpent.setCellValueFactory(new PropertyValueFactory("getTimeSpent"));
timeSpent.setCellFactory(TextFieldTableCell.forTableColumn());
commentTimeLog.setCellValueFactory(new PropertyValueFactory("getComment"));
commentTimeLog.setCellFactory(TextFieldTableCell.forTableColumn());
timeSpent.setOnEditCommit(new EventHandler<CellEditEvent<JiraAuth, String>>() {
public void handle(CellEditEvent<JiraAuth, String> t) {
JiraAuth.setTimeSpent(t.getNewValue());
}
});
commentTimeLog.setCellFactory(TextFieldTableCell.forTableColumn());
commentTimeLog.setOnEditCommit(new EventHandler<CellEditEvent<JiraAuth, String>>() {
public void handle(CellEditEvent<JiraAuth, String> t) {
JiraAuth.setWorkLogComment(t.getNewValue());
int i = t.getTablePosition().getRow();
String abc = table.getColumns().get(0).getCellData(i).toString();
String finalStr = abc.substring(abc.indexOf("]") + 1);
JiraAuth.setWorkLogJiraKey(finalStr);
}
});
table.getColumns().setAll(jiraKey, jiraSummary, jiraPriority, jiraAssignee, jiraIssueType);
IssuesJsonParser issueObject = new IssuesJsonParser();
ObservableList<Issues> data = issueObject.issueJsonList();
table.setItems(data);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
return table;
}
upon calling the refresh button,
buttons[0] = new Button("Refresh");
buttons[0].setOnAction(event->{
initTable().refresh();
});
nothing happens. Please help!!

TypeInitializationException with separate Class

i have a little program to monitor my oracle DB's.
So i have a Class DBConn: (extremely shortened)
class DBConn
{
private OracleConnection conn_oraconn = new OracleConnection();
OracleCommand cmd_oracmd;
static string str_oraconn;
OracleDataReader dr;
Logger log = new Logger();
private String str_cname;
public DBConn(String str_connname)
{
str_cname = str_connname;
}
}
In the main Form i initialize this by: (extremely shortened)
public partial class frm_main : Form
{
TNSEntries availtns = new TNSEntries();
bool gettns = false;
Logger applog = new Logger();
//List<DBConn> dbconn = new List<DBConn>();
DBConn mydb;
String std_user, std_password, std_db;
private void btn_connect_Click(object sender, EventArgs e)
{
mydb = new DBConn(cmb_dbs.SelectedItem.ToString());
}
}
So i start the programm and if i click the button i get the error in the line
private OracleConnection conn_oraconn = new OracleConnection(); in CLass DBConn. I don't understand why.
If i put this member directly under public partial class frm_main : Form it works.
i found the error.
The "OracleDataAccess.ddl" was the reason. I switched the version and all is fine.
Thanks!

Insertion operation in SqlCe in windows phone

I am trying to insert some data into mydatabase but getting error like "Can't perform Create, Update, or Delete operations on 'Table(Dic)' because it has no primary key."
My database name is "condrokotha_new.sdf" and it has a table named "dic" which have 2 columns named "english" and "bangla". I made this database in another C# project in vs 2010. Then i used this database into my windowsphone project. I can show data from database but when i try to insert data i am getting error.
Here is my code:
public partial class MainPage : PhoneApplicationPage
{
condrokotha_newContext db = null;
// Constructor
public MainPage()
{
InitializeComponent();
db = new condrokotha_newContext(condrokotha_newContext.ConnectionString);
db.CreateIfNotExists();
db.LogDebug = true;
}
private void fav_Click(object sender, RoutedEventArgs e)
{
add_new_words("cintakhela","ami");
}
private void add_new_words(string e_word,string b_word)
{
using (condrokotha_newContext context = new condrokotha_newContext(condrokotha_newContext.ConnectionString))
{
Dic d = new Dic();
d.English = e_word;
d.Bangla = b_word;
context.Dics.InsertOnSubmit(d);
context.SubmitChanges();
}
}
}
My data context code like these :
public static string ConnectionString = "Data Source=isostore:/condrokotha_new.sdf";
public static string ConnectionStringReadOnly = "Data Source=appdata:/condrokotha_new.sdf;File Mode=Read Only;";
public static string FileName = "condrokotha_new.sdf";
public condrokotha_newContext(string connectionString) : base(connectionString)
{
OnCreated();
}
#region Extensibility Method Definitions
partial void OnCreated();
#endregion
public System.Data.Linq.Table<Dic> Dics
{
get
{
return this.GetTable<Dic>();
}
}
}
[global::System.Data.Linq.Mapping.TableAttribute(Name="dic")]
public partial class Dic
{
private string _English;
private string _Bangla;
public Dic()
{
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Name="english", Storage="_English", DbType="NVarChar(1000)")]
public string English
{
get
{
return this._English;
}
set
{
if ((this._English != value))
{
this._English = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Name="bangla", Storage="_Bangla", DbType="NText", UpdateCheck=UpdateCheck.Never)]
public string Bangla
{
get
{
return this._Bangla;
}
set
{
if ((this._Bangla != value))
{
this._Bangla = value;
}
}
}
}
`
How can i insert my data into my database??
Is there anyone who can help in this??
For example you have this
SampleDataContextDataContext db = new SampleDataContextDataContext();
Employee emp = new Employee() {
FirstName = "Experts",
Lastname = "Comment",
Address = "rs.emenu#gmail.com"
}
db.Employees.InsertOnSubmit(emp);
db.SubmitChanges();
The above code will give you same error when u try to insert a new row. The reason is that LINQ does not provide the facility to insert data into a table without a primary key. At this point you have two options.
1.Create a store procedure and call it from LINQ.
SampleDataContextDataContext db = new SampleDataContextDataContext();
db.InsertEmployeeData("Experts","Comment", "rs.emenu#gmail.com");
Here InsertEmployeeData is a a stored procedure, and called it from the code.
2.Create an insert statement and execute using LINQ.
SampleDataContextDataContext db = new SampleDataContextDataContext();
string insertStatement = "Insert into Employee values('Experts', 'Comment','rs.emenu#gmail.com')";
db.ExecuteQuery<Employee>(insertStatement);
Here insert query is normal sql query and executed using the the LINQ ExecuteQuery method.

Resources