I am trying to develop a simple application with a simple SQLite database. I am new to C# so I may have missed something obvious. When I run the following code, it returns the error:
SQL logic error or missing database.No such table: Customer
(edit: Yes I have created that table within the database, I performed/confirmed this using the sqlite command prompt
Here is my code:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
namespace TestPersonDatabase
{
public partial class DBconnection : Form
{
SQLiteDatabase sqliteDb = new SQLiteDatabase();
public DBconnection()
{
InitializeComponent();
}
// Using SQLite
private void btnInsert_Click(object sender, EventArgs e)
{
Dictionary<String, String> data = new Dictionary<String, String>();
data.Add("CustomerId", this.fieldInsertId.Text);
data.Add("FirstName", this.fieldInsertFName.Text);
data.Add("LastName", this.fieldInsertLName.Text);
data.Add("MobileNumber", this.fieldInsertDob.Text);
try
{
sqliteDb.Insert("Customer", data);
}
catch(Exception error)
{
MessageBox.Show(error.Message);
}
}
}
class SQLiteDatabase
{ String dbConnection;
public SQLiteDatabase()
{
dbConnection = "Data Source=" + (global::TestPersonDatabase.Properties.Resources.database);
}
public bool Insert(String tableName, Dictionary<String, String> data)
{
String columns = "";
String values = "";
Boolean returnCode = true;
foreach (KeyValuePair<String, String> val in data)
{
columns += String.Format(" {0},", val.Key.ToString());
values += String.Format(" '{0}',", val.Value);
}
columns = columns.Substring(0, columns.Length - 1);
values = values.Substring(0, values.Length - 1);
try
{
this.ExecuteNonQuery(String.Format("insert into {0}({1}) values({2});", tableName, columns, values));
}
catch (Exception fail)
{
MessageBox.Show(fail.Message);
returnCode = false;
}
return returnCode;
}
Obviously the code above is two different classes put together. Just made it easier for you to read.
It seems like it cannot find the database file. But I appear to have linked it up correctly (its in the solution resources). Any help would be very much appreciated as I am a bit stumped! Thanks :)
You never opened your sql connection try:
dbConnection.Open(); //Initiate connection to the db
It doesn't look like you've created the table.
Before you input any data you'll need to create the table using something like:
this.ExecuteNonQuerySQL("CREATE TABLE Customers(CustomerID INTEGER PRIMARY KEY, sPassword TEXT, CustomerName TEXT);");
Once you've created the table the insert code you have should work fine.
Related
With a csv file looking like this:
usernames,passwords
us1,ps1
us2,ps2
I would like all usernames in one array an all passwords in another.
Current code:
(Trying to make a login system that interacts with a database.)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.Globalization;
namespace Login
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string[] usernames = new string[] { };
string[] passwords = new string[] { };
private void btnLogin_Click(object sender, EventArgs e)
{
lblLoginSucsess.Text = "";
for (int i = 0; i < Math.Min(usernames.Length, passwords.Length); i++)
{
if ((usernames[i].ToLower() == txtUsnme.Text.ToLower()) && (passwords[i].ToLower() == txtPass.Text.ToLower()))
{
lblLoginSucsess.Text = $"Welcome, {txtUsnme.Text}.";
// run calc
Process.Start("C:/Users/finch/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/HP Inc/Calculator.appref-ms");
}
}
}
}
}
If you can help, Thanks.
Instead of having two separate list, it would be better if you had a Dictionary of UserName/Password. You could read CSV and convert to dictionary by
var dataLines = File.ReadAllLines(filePath);
var userPassDictionary = dataLines.Skip(1)
.Select(x=> x.Split(new[]{','}, StringSplitOptions.RemoveEmptyEntries))
.ToDictionary(x=> x.First().ToLower(),v=>v.Last());
Now you could access validate the user as
if (userPassDictionary[txtUsnme.Text.ToLower()] == txtPass.Text)
{
}
Note
It was also curious to note that your were comparing password case-insensitevely. While it might depend on the business requirement, most often than not, passwords are case-sensitive. Wanted to highlight it, just in case, it was by accident.
Please someone help me - I have a problem.
I'm trying to code an alternate database for a program I am writing in C#. You see on the website I managed to do it with an if..
This is my php code:
//database connection
$conexion = #mysqli_connect("localhost","todo","todo","dbdaq");
//if mainserver connection is not made then it connects to secondary server
if (!$conexion){
$conexion = mysqli_connect("192.168.0.12","todo","","dbdaq");
}
And that works in PHP, but when I try to write something like that in C#, I can't manage to do it.
Here is my database connection class in C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace ComunicacionCSharp
{
class ConexionBD
{
public static MySqlConnection ObtenerConexion()
{
MySqlConnection Conectar = new MySqlConnection("Server =localhost; database = dbdaq ; Userid = root; password =");
return Conectar;
}
}
}
NOTE: this class is called from my main GUI interface.
namespace ComunicacionCSharp
{
public partial class Login : Form
{
MySqlConnection conn = ConexionBD.ObtenerConexion();
public string usuario;
public Login()
{
InitializeComponent();
}
}
}
Can someone please help me? I use to have another version of the database connection with an error message if the connection is not found, but I left coding in C# for a while and could not find that piece of code anymore, and I don't remember how to do it :(
mysqli_connect returns a handle to an open connection and in your C# code you pass an unopened connection. You must change a bit your code, something like this:
public static MySqlConnection ObtenerConexion()
{
MySqlConnection Conectar = null;
try
{
Conectar = new MySqlConnection(yourFirstConnectionString);
Conectar.Open();
}
catch
{
try
{
Conectar = new MySqlConnection(yourSecondConnectionString);
Conectar.Open();
}
catch{ }
}
return Conectar;
}
Remember to check the connection wherever you use it, if both connections fail it will return null.
i'm rather new and am trying to create a C# program that retrieves post from Facebook using FB API.
I have a word count feature which checks against a negative word dictionary.
This means that it would display the negative word along with its frequency occurrence.
The problem i'm facing now is that, i want to display the posts that contains this negative words. However, if the negative word exists 3 times in the post, the post would appear thrice. How do i solve this problem?
Below is my code:
(For designer)
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.IO;
namespace empTRUST
{
public partial class PostAnalysis : Form
{
DBStatusDL ad;
string target_fbid;
public PostAnalysis(string target_fbid)
{
InitializeComponent();
this.target_fbid = target_fbid;
ad = new DBStatusDL();
}
private void button_Displayposts_Click(object sender, EventArgs e)
{
int i = 1;
var dir = new DirectoryInfo(Application.StartupPath + "\\Dictionary"); //Load the dictionary from debug folder
var ed = new matchingWordsWithPosts();
var rows = ad.LoadStatus(target_fbid); //Call the load status function based on fb_id
foreach (FileInfo file in dir.GetFiles()) //For loop, to loop through files
{
var dict = File.ReadAllLines(dir.FullName + "\\" + file);
foreach (var row in rows)
{
List<DataRow> words = ed.countWordsInStatus(row, dict); // Retrieves word dictionary returned from function
foreach (var word in words)
{
var item = new ListViewItem(new[] { i.ToString() ,word["Status_message"].ToString(), word["Status_time"].ToString() });
listViewPosts.Items.Add(item);
i++;
}
}
}
}
private void button_Back_Click(object sender, EventArgs e)
{
this.Close();
var abc = new AnalysisPage(target_fbid);
abc.Show();
}
}
}
(For class)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Data;
namespace empTRUST
{
class matchingWordsWithPosts
{
public List<DataRow> countWordsInStatus(DataRow status, string[] dictArray)
{
List<DataRow> statusList = new List<DataRow>();
var words = new Dictionary<string, int>(StringComparer.CurrentCultureIgnoreCase); // local word dictionary is created here
foreach (var dictEntry in dictArray)
{
var wordPattern = new Regex(#"\w+");
string smallDictEntry = dictEntry.ToLower();
foreach (Match match in wordPattern.Matches(status["Status_message"].ToString()))
{
if (match.ToString() == smallDictEntry)
{
statusList.Add(status);
}
}
}
return statusList; // returns local word dictionary to receiving end
}
}
}
Because you didn't provide the countWordsInStatus() function, I can't know if that's the problem. However, it looks like the problem is that that function continues going through a post even if it has already matched one such word. To fix this, you could put continue; (or perhaps a break;, depending on the code you're using) after adding a post to the list you're returning. This would have the loop skip to the next post, and make sure it doesn't continue counting words in the post that has already had a match.
If you post that function, it should be much easier to understand the issue.
After a word is matched and you process the post exit the loop.
I have an Oracle package that gives a list of facilities based on user ID. It is used to determine access. We have several projects that use this package already but they are all VB and WebForms - we are moving over to C# and MVC and this is the first project like that utilizing this package.
When attempting to run a query in the package, I get a System.InvalidOperationException: The number of parameters does not match number of values for stored procedure.
Procedure spec (I do not have access to the body and this part cannot be edited as it is used extensively in other applications):
Procedure GetFacilitiesByUser
(
p_EmpNo IN int,
cur_OUT out sys_refcursor
);
And my C#:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Oracle;
namespace MvcApplication1.DataAccess
{
public class InpatientSecurity
{
public List<string> GetHospitals(int EmployeeNumber)
{
var response = new List<string>() { };
object[] _params = { EmployeeNumber };
IDataReader dr = ExecuteQuery(
"connection string",
"datawarehouse.Access.GetFacilitiesByUser",
_params
);
while (dr.Read())
{
response.Add("test");
}
return response;
}
private IDataReader ExecuteQuery(string provider, string procedure, params object[] args)
{
var _db = new OracleDatabase(provider);
object[] objArr = new object[args.Length];
args.CopyTo(objArr, 0);
if (args.Length > 1)
{
objArr[objArr.Length - 1] = System.DBNull.Value;
}
IDataReader reader = _db.ExecuteReader(procedure, objArr); /* Exception thrown here */
_db = null;
return reader;
}
}
}
I did not write the original VB code used to access this procedure, this is just a
As usual, I figured it out shortly after posting. The objArr array needs to be of length 2, I guess to take into account the ref cursor? Changing the following line in ExecuteQuery() fixed the issue.
Change this:
object[] objArr = new object[args.Length];
To this:
object[] objArr = new object[args.Length + 1];
Below is what I use to log into the database using linq and then I use C# expressions to gather the data I want. The next thing I want to do is convert this data into an XML any Ideas?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Data;
namespace VcacManagementTools.BuildProfiles
{
public static class BuildProfileTools
{
public static ICollection<string> GetExistingBuildProfileNames(string repositoryHostname,
string repositoryUsername,
string repositoryPassword)
{
var url = string.Format("https://{0}/repository/data/ManagementModelEntiti.svc", repositoryHostname);
var managementModelClient = new DynamicOps.ManagementModel.ManagementModelEntities(new Uri(url))
{
Credentials = new NetworkCredential(repositoryUsername, repositoryPassword)
};
return managementModelClient
.GlobalProfiles
.Select(gp => gp.ProfileName)
.ToList();
The Output I recieve is a list of values
If I understood you well, you want to take the data (the list contains the data from the database) and put it in XML file. I used variables to show where to put each data.
In case you have an XML:
try
{
doc = XDocument.Load(spath, LoadOptions.SetBaseUri);
foreach(String propertyData in dataList)
{
XElement root = new XElement(ElementName);
root.Add(new XElement("property1", propertyData));
doc.Element(MainElement).Add(root);
}
doc.Save(spath);
}
catch (Exception)
{
}