Syntax error in From clause (easiest from clause possible) - c#

I have an error in my easiest From clause (ErrorCode: -2147217900) and I do not know why...
Here my Code:
static string ConnString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=E:\\P-OT-MT\\P-OT-DB.accdb; Jet OLEDB:Database Password=*************;";
public static DataSet DS_USERS;
public static void INIT_DS()
{
// Initialize the USERS dataset and write the database information to it
DS_USERS = new DataSet();
string SQL = "SELECT * FROM USER;";
using (OleDbConnection Conn = new OleDbConnection(ConnString))
{
Conn.Open();
OleDbCommand cmd = new OleDbCommand(SQL, Conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(DS_USERS);
cmd.Dispose();
adapter.Dispose();
Conn.Close();
}
}
I dont get where the error is... the Table USER is existant and the location of the Database is also correct... The password is correct too...
I hope you can help me

USER is a reserved word in MS Access.
See: List of reserved words in Access 2002 and in later versions of Access
You have to escape the word using [].
Use: string SQL = "SELECT * FROM [USER];";

Related

ASP.NET getting data from SQL Server

I am trying to get the name of the employee from the database and fill it in the textbox for the respective employee id.
I tried this code but nothing is happening on the page. It just reloads and the textbox (name) is left blank only.
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-0FUUV7B\SQLEXPRESS;Initial Catalog=EmployeeDetails;Integrated Security=True");
con.Open();
           
SqlCommand cmd = new SqlCommand("select * from ProfessionalDetails where EmpId='"+EmployeeId.Text+"'", con);
          
SqlDataReader da = cmd.ExecuteReader();
while (da.Read())
{
    Name.Text = da.GetValue(1).ToString();
}
            
con.Close();
Better solution is to execute the sql statement through Parameterized value.
The details of that process is given below:
using (SqlConnection con = new SqlConnection(live_connectionString))
{
using (SqlCommand cmd = new SqlCommand("Query", con))
{
con.Open();
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#EmpId", employeeId);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
var ds = new DataSet();
da.Fill(ds);
string? name = ds.Tables[0].Rows[1]["Variable name"].ToString();
Name.Text =name;
};
}
}
As mentioned above in comments, you have lot of issues.
you should use using with the connection to dispose of them.
You should use parameterized queries to avoid SQL injection.
Put your code in try catch so that you can easily identify the root cause of the issue.
Define the connection string in config file three than defining in the c# code.
You don’t need to select all the columns. And please avoid select * in the query, instead just write your column name, as you want to select only one column here.
You can use ExecuteScalar, it’s used when you are expecting single value.
And first make sure that textbox has the expected value when you are calling this query.
As noted, use paramters, and BETTER use STRONG typed paramters.
And no need to use a dataset, this is a single table - so use a datatable.
thus:
string strSQL =
#"select * from ProfessionalDetails where EmpId= #ID";
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmd = new SqlCommand(strSQL, con))
{
con.Open();
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = EmployeeID.Text;
DataTable rstData = new DataTable();
rstData.Load(cmd.ExecuteReader());
if (rstData.Rows.Count > 0)
Name.Text = rstData.Rows[0]["Name"].ToString();
}
}

Updating excel values in data grid view on certain condition

I need to fetch a row value from an excel sheet in data grid view in winform.
I’m able to display the entire excel sheet in the datagridview. But, I need to display particular rows in the grid based on a current date condition.
public DataTable ReadExcel2(string fileName, string fileExt)
{
string connectionstring ;
DataTable dtexcel2 = new DataTable();
connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=YES';";
OleDbConnection connection = new OleDbConnection(connectionstring);
OleDbCommand oconn = new OleDbCommand("Select * From [POSFailures$] WHERE Date=#date");
oconn.Connection = connection;
try
{
oconn.Parameters.AddWithValue("#date", DateTime.Now.ToString("MM/dd/yyyy"));
connection.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
sda.Fill(dtexcel2);
connection.Close();
}
catch (Exception)
{
}
return dtexcel2;
}
Thanking you in advance
What seems to be happening here is that the Date parameter is not being honored, as you are getting back all of the rows. So, I used Google to figure out how to properly add parameters when using OleDbConnection. I found this:
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement
Source: https://learn.microsoft.com/en-us/dotnet/api/system.data.oledb.oledbcommand.parameters?redirectedfrom=MSDN&view=netframework-4.8#System_Data_OleDb_OleDbCommand_Parameters
Using the example on that page, try changing your code to this:
string connectionstring;
DataTable dtexcel2 = new DataTable();
connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=YES';";
OleDbConnection connection = new OleDbConnection(connectionstring);
OleDbCommand command = new OleDbCommand("Select * From [POSFailures$] WHERE Date = ?");
command.Parameters.Add(new OleDbParameter(DateTime.Now.ToString("MM/dd/yyyy"), OleDbType.Date));
command.Connection = connection;
try
{
connection.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(command);
sda.Fill(dtexcel2);
connection.Close();
}
catch (Exception)
{
}
Please note that i've not tested this, so I can't promise it will work. But, the main point is... the answer is out there! You just need to go looking for it.

Trying to create a login form using dapper to connect to SQL but I can't get the DataAdapter to work

Here is my code
public class LoginFunction
{
public DataTable User (string username, string pword)
{
using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(ConnectionHelper.CnnVal("GymDB")))
{
var query = ("Select * from [USER] where username = '{username}' and password = '{pword}'");
SqlDataAdapter sda = new SqlDataAdapter(query, connection);
DataTable dtbl = new DataTable();
sda.Fill(dtbl);
}
}
}
}
The error im getting is "cannot convert from 'System.Data.IDbConnection' to 'string'".
The error is with the connection argument for SqlDataAdapter - I thought this would get the SQL connection from the IDbConnection.
I'm sorry I can not comment yet.
Try to change IDbConnection to SqlConnection and var query to string query and take away the parenthesis.
See if it works!?

Search and display certain table element

I'm trying to search my local database table and simply display all it's columns.
I start my sending in
SearchID("1234");
My code so far:
private static void SearchID(string CostumerID)
{
string conStr = #"Data Source = C:\Users\secwp_000\documents\visual studio 2012\Projects\Module5\Module5\Orderdatabase.sdf";
DataSet ds = new DataSet();
SqlCeConnection con = new SqlCeConnection(conStr);
SqlCeCommand cmd = new SqlCeCommand("SELECT * FROM [Order]", con);
SqlCeDataReader dr = cmd.ExecuteReader();
SqlCeDataAdapter adapt = new SqlCeDataAdapter(cmd);
adapt.Fill(ds, "Order");
while (dr.Read())
{
string str = (string)dr[1];
if (str == CostumerID)
{
Console.WriteLine(str);
}
}
}
Where am I thinking wrong?
It stops on
SqlCeDataReader dr = cmd.ExecuteReader();
saying i don't have a connection. But just sounds wierd, because I've just had connection..
You have to open connection using
If(con.state.toString()=="closed")
con.open();
I observe a fault in your query why are you compare your result after fetch from database.you can directly filter in SQL query
Select * from order where table.customer_Id = customerId
You have a connection but you haven't opened it yet:
con.Open();
adapt.Fill(ds, "Order");
con.Close();
In addition you should use using statements for disposable objects like SqlConnection and SqlCommand to make sure they will be disposed properly:
using(SqlCeConnection con = new SqlCeConnection(conStr))
using(SqlCeCommand cmd = new SqlCeCommand("SELECT * FROM [Order]", con))
{
}
I feel so stupid for not seeing this, haha. And it worked! But it wont display anything from the table,
while (dr.Read())
{
string str = (string)dr[1];
if (str == CostumerID)
{
Console.WriteLine(str);
}
}
Following instructions given to me, there is nothing wrong with this code, and it could display Order with costumerID 1234.

C# Read from .DBF files into a datatable

I need to connect to a .dbf file in visual Studio using C# and populate a data table. Any ideas? I can currently view the tables in Visual Fox Pro 9.0
Code I have tried and failed, keep getting
External table is not in the expected format.
private OleDbConnection conn;
private OleDbCommand cmd;
private OleDbDataReader dr;
private string sqlStr = "";
private DataSet myDataSet;
private OleDbDataAdapter myAdapter;
void test2()
{
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\PC1\Documents\\Visual FoxPro Projects\\;Extended Properties=DBASE IV;");
conn.Open();
sqlStr = "Select * from Clients.dbf";
//Make a DataSet object
myDataSet = new DataSet();
//Using the OleDbDataAdapter execute the query
myAdapter = new OleDbDataAdapter(sqlStr, conn);
//Build the Update and Delete SQL Statements
OleDbCommandBuilder myBuilder = new OleDbCommandBuilder(myAdapter);
//Fill the DataSet with the Table 'bookstock'
myAdapter.Fill(myDataSet, "somename");
// Get a FileStream object
FileStream myFs = new FileStream
("myXmlData.xml", FileMode.OpenOrCreate, FileAccess.Write);
// Use the WriteXml method of DataSet object to write XML file from the DataSet
// myDs.WriteXml(myFs);
myFs.Close();
conn.Close();
}
This code worked for me!
public DataTable GetYourData()
{
DataTable YourResultSet = new DataTable();
OleDbConnection yourConnectionHandler = new OleDbConnection(
#"Provider=VFPOLEDB.1;Data Source=C:\Users\PC1\Documents\Visual FoxPro Projects\");
// if including the full dbc (database container) reference, just tack that on
// OleDbConnection yourConnectionHandler = new OleDbConnection(
// "Provider=VFPOLEDB.1;Data Source=C:\\SomePath\\NameOfYour.dbc;" );
// Open the connection, and if open successfully, you can try to query it
yourConnectionHandler.Open();
if (yourConnectionHandler.State == ConnectionState.Open)
{
string mySQL = "select * from CLIENTS"; // dbf table name
OleDbCommand MyQuery = new OleDbCommand(mySQL, yourConnectionHandler);
OleDbDataAdapter DA = new OleDbDataAdapter(MyQuery);
DA.Fill(YourResultSet);
yourConnectionHandler.Close();
}
return YourResultSet;
}
Visual FoxPro DBFs are NOT dBase IV DBFs, and as such are unreadable by most versions of Microsoft Access's Jet database engine. (MSDN has some specifics, if you care.)
You'll need to either export the DBF from FoxPro into an actual dBase format, or you'll need to have C# open it using the Visual FoxPro OLEDB provider.
Once you have the provider installed, you'll need to change the "Provider" argument of your connection string to the following, assuming your DBF is in that folder.
Provider=VFPOLEDB.1;Data Source=C:\Users\PC1\Documents\Visual FoxPro Projects\;
(Use an #"" string format; you missed a slash in the code sample, between PC1 and Documents.)

Categories