A simple "select * from tablename" sql query works for a table named 'mode' but not for a table named 'user'. Why?
Both tables have 2 columns. If I run the program with the "mySQL" variable as "SELECT * FROM mode" it works fine. If I put the user table instead, which means the mySQL would have been "SELECT * FROM user" then it raises an exception which says "Syntax error in FROM clause.". How can this be?
Here is the code:
static void Main(string[] args)
{
String connectionstring = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=Accounts.mdb";
OleDbConnection conn;
conn = new OleDbConnection(connectionstring);
try
{
conn.Open();
}
catch (Exception)
{
Console.Write("Could not connect to database");
}
String mySQL = "SELECT * FROM user";
OleDbCommand cmd = new OleDbCommand(mySQL, conn);
OleDbDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.Write(String.Format("{0}\n,{1}\n", rdr.GetValue(0).ToString(), rdr.GetValue(1).ToString()));
}
Console.Read();
}
Because USER is a reserved word in MS-Access
Change you query to encapsulate it between square brakets
SELECT * FROM [User]
albeit I suggest you to change the name of the table
Do like Steve said. And a suggestion for your code:
String connectionstring = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=Accounts.mdb";
OleDbConnection conn = null;
OleDbCommand cmd = null;
OleDbDataReader rdr = null;
String mySQL = "SELECT * FROM [user]";
try
{
conn = new OleDbConnection(connectionstring);
conn.Open();
cmd = new OleDbCommand(mySQL, conn);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.Write(String.Format("{0}\n,{1}\n", rdr.GetValue(0).ToString(), rdr.GetValue(1).ToString()));
}
Console.Read();
conn.Close();
}
catch (Exception ex)
{
Console.Error.Write("Error founded: " + ex.Message);
}
finally
{
if (conn != null) conn.Dispose();
if (cmd != null) cmd.Dispose();
if (rdr != null) rdr.Dispose();
}
Related
I'm trying to check if the username is already in use in C# database and it's giving me this error
SqlConnection cn = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\admin\Desktop\241 Project sem 1 2020-2021\Online Banking - ITIS 241 project group 9\UobBankDatabase.mdf; Integrated Security = True; Connect Timeout = 30");
cn.Open();
SqlCommand cmd = new SqlCommand("select * from LoginTable where user_name='" + textBox1.Text + "'", cn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
dr.Close();
MessageBox.Show("Username Already exist please try another ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
dr.Close();
}
and yes I'm a newbie
Use this:
SqlCommand cmd = new SqlCommand("Select count(*) from LoginTable where user_name='" + textBox1.Text + "'", cn);
Then:
var dr = cmd.ExecuteScalar();
if (dr != null)
{
//Exists
}
else
{
//Unique username
}
Google it please:
Since the error is SqlException: Invalid object name 'Movie' , that
means the table named 'Movie' has not created or the Database you are
referring has not created. To see if the Database or table 'Movie' has
created, open SQL Server Object Explorer and check the Database name
is the same as in appsettings. json
And Please tell us at what line do you get that?
Is that this line =>if (dr.Read())
Let's extract method for the check:
private static bool NameAvailable(string name) {
//DONE: wrap IDisposable into using
using (SqlConnection cn = new SqlConnection("Connection String Here")) {
cn.Open();
//DONE: keep Sql readable
//DONE: make Sql parametrize
//DONE: select 1 - we don't want entire record but a fact that record exists
string sql =
#"select 1
form LoginTable
where user_name = #prm_user_name";
using (var cmd = new SqlCommand(sql, cn)) {
cmd.Parameters.Add("#prm_user_name", SqlDbType.VarChar).Value = name;
using (var dr = cmd.ExecuteReader()) {
return !dr.Read(); // Not available if we can read at least one record
}
}
}
}
Then you can put
if (!NameAvailable(textBox1)) {
// Let's be nice and put keyboard focus on the wrong input
if (textBox1.CanFocus)
textBox1.Focus();
MessageBox.Show("Username Already exist please try another ",
"Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
some changes only.it is better to get what is the error than a temporary solution so print your query first and run it in the sqlserver . also add initial catalog instead of attacjing mdf files its way better in my opinion.
<connectionStrings>
<add name="stringname" connectionString="Data Source=mssql;Initial Catalog=databasename; Persist Security Info=True;User ID=sa;Password=*****;MultipleActiveResultSets=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
using a connection string instead also
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["stringname"].ConnectionString);
cn.Open();
string query = "select * from LoginTable where user_name='" + textBox1.Text.ToString() + "'";
SqlCommand cmd = new SqlCommand(query, cn);
SqlDataReader dr = cmd.ExecuteReader();
//print query if error and comment the execute reader section when printing the query to know the error Respone.Write(query);
if (!dr.HasRows)
{
// ur code to insert InsertItemPosition values
}
else
{
//show username exist
}
dr.Close();
Try this:
string conString = ConfigurationManager.ConnectionStrings["YourConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("SELECT COUNT(UserName) as UserCount FROM LoginTable WHERE user_name = #user_name", con))
{
con.Open();
cmd.Parameters.AddWithValue("#user_name", TextBox1.Text);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows)
{
if(Convert.ToInt32(dr["UserCount"].ToString()) >= 1)
{
// Exists
}
else
{
// Doesn't Exist
}
}
}
con.Close();
}
}
These are the tables in my project:
I am trying to update a DataGridView so that it displays the data of the user who is logged in.
I am getting the error: 'Must declare scalar variable '#CurrentUserID'... I think this is because I cannot convert the value to an int but if this is the case how do I fix the problem?
This is my code so far:
//Find ID of user who is logged in
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\n0740572\Projects\newest\CW\CW\Database1.mdf;Integrated Security=True");
SqlCommand command = new SqlCommand("select UserID from Users where Username = '"+loggedInLabel.Text+"' ", conn);
try
{
conn.Open();
SqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
int currentUserID = reader.GetInt32(reader.GetOrdinal("UserID"));
command.Parameters.Add("#CurrentUserID", SqlDbType.Int);
command.Parameters["#CurrentUserID"].Value = currentUserID;
//update datagridview
string dgvconn = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\n0740572\Projects\newest\CW\CW\Database1.mdf;Integrated Security=True";
string sql = "select * from Records where UserID = #CurrentUserID";
SqlConnection connection = new SqlConnection(dgvconn);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Records");
connection.Close();
dataGridView.DataSource = ds;
dataGridView.DataMember = "Records";
}
reader.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
Just in case anyone else was stuck with it.
I solved it by removed the code where I added the parameters and replacing it with :
dataadapter.SelectCommand.Parameters.AddWithValue("#CurrentUserID", currentUserID);
Thanks for the help!
You have many errors in your code, you're not disposing anything and re-using the command in a invalid way (while the reader is executing).
You're not using parameters. You're not re-using the SQL Connection. You're not adding parameters in the correct way.
This is how the code should look
try
{
DataSet records = new DataSet();
using (SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\n0740572\Projects\newest\CW\CW\Database1.mdf;Integrated Security=True"))
{
int? userId = null;
using (SqlCommand command = new SqlCommand("select UserID from Users where Username = #Username", conn))
{
command.Parameters.Add("#Username", SqlDbType.NVarChar).Value = loggedInLabel.Text;
conn.Open();
using (SqlDataReader reader = command.ExecuteReader())
if (reader.Read())
userId = reader.GetInt32(reader.GetOrdinal("UserID"));
conn.Close();
}
if (userId == null) // No row found
throw new ApplicationException("User not found");
using (SqlCommand command = new SqlCommand("select * from Records where UserID = #CurrentUserID", conn))
{
command.Parameters.Add("#CurrentUserID", SqlDbType.Int).Value = userID.Value;
// SqlDataAdapter opens and closes the connection itself.
using (SqlDataAdapter dataadapter = new SqlDataAdapter(command))
dataadapter.Fill(records , "Records");
}
}
//update datagridview
dataGridView.DataSource = records ;
dataGridView.DataMember = "Records";
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
You should also combine SQL Queries
select UserID from Users where Username = #Username and select * from Records where UserID = #CurrentUserID can be combined into this:
select Records.*
from Records
join Users
on Users.UserID = Records.UserID
where Users.Username = #Username
Then you only have to supply the Username and you'll get the records if everything is there.
I want insert some data to localdatabace and insert is successfully done but don't show in my datagridview tile second insert do for debog it I Call Select All end of my insert and see the last insert don't show in it but whene i insert a next data , last data will be showing can every one help me pleas?
public void connect()
{
String conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\hana\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection sql = new SqlConnection(conString);
String sqll = "Insert into TblBank (txtTodayDate" +
",txtSahebanHesab" +
",txtShobe" +
",txtShomareMoshtari" +
",txtShoareHesab" +
",cmbNoeHesab" +
",txtSarresid" +
")";
try
{
sql.Open();
SqlDataAdapter sda = new SqlDataAdapter(sqll, sql);
SqlCommand sc = new SqlCommand(sqll,sql);
sc.Parameters.AddWithValue("todayDate", new PersianDateTime(dtpTodayDate.the_date).ToString("yyyy/MM/dd"));
sc.Parameters.AddWithValue("sahebanHesab", txtSahebHesabName.Text);
sc.Parameters.AddWithValue("shobe", txtshobe.Text);
sc.Parameters.AddWithValue("shomareMoshtari", txtShomareMoshtari.Text);
sc.Parameters.AddWithValue("shoareHesab", txtShomareHesab.Text);
sc.Parameters.AddWithValue("noeHesab", cmbNoeHesab.SelectedIndex);
sc.Parameters.AddWithValue("sarresid", txtSarResidMah.Text);
sc.ExecuteNonQuery();
sql.Close();
select();
}
catch (Exception ex)
{
}
}
and select is
private void select()
{
String conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\hana\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection cn = new SqlConnection(conString);
String sqlString = "SELECT * FROM TblBank Order BY Id desc ";
SqlConnection sql = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand(sqlString, cn);
try {
sql.Open();
SqlDataAdapter sa = new SqlDataAdapter(sqlString, sql);
using (SqlDataReader read = sa.SelectCommand.ExecuteReader())
{
if (read.Read())
{
DataTable dt = new DataTable();
dt.Load(read);
this.tblBankDataGridViewX.DataSource = dt;
}
}
sql.Close();
}
catch (Exception ex)
{
}
}
The DataReader.Read() method will iterate result set before DataTable.Load(). Because the DataReader is a forward-only stream, it has empty result set when DataTable.Load() executes and DataTable content is still empty while setting DataSource for DataGridView. Try DataReader.HasRows property to check result set availability:
using (SqlConnection cn = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(sqlString, cn))
{
try
{
cn.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
// check if the reader returns result set
if (read.HasRows)
{
DataTable dt = new DataTable();
dt.Load(read);
this.tblBankDataGridViewX.DataSource = dt;
}
}
}
catch (Exception ex)
{
// do something
}
}
}
i want to write data into a local database table.
When i run the code there are no erros and when i count the rows after the insert statement the message box shows me that a row was inserted.
But when i close the programm and look in my database there are no new rows.
I'm using C# and Visual Studio 2013.
Do anybody know what the problem is?
Thank you.
String connection = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Datenbank.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection cnn = new SqlConnection(connection);
cnn.Open();
String query = "INSERT INTO Customer (ID, Name) VALUES (#id, #name)";
SqlCommand command = new SqlCommand(query, cnn);
command.Parameters.AddWithValue("#id", 1);
command.Parameters.AddWithValue("#name", 'John');
SqlDataReader reader;
command.ExecuteNonQuery();
query = "Select count(ID) from Customer";
command = new SqlCommand(query, cnn);
reader = command.ExecuteReader();
while (reader.Read())
{
MessageBox.Show(reader[0].ToString());
}
reader.Close();
Try like this:
try {
int rowsAffected = command.ExecuteNonQuery();
if (0 < rowsAffected)
MessageBox.Show("Success!");
else
MessageBox.Show("Failed!");
} catch (SqlException ex) {
MessageBox.Show(ex.Message);
} finally {
if (cnn.State == ConnectionState.Open)
cnn.Close();
}
Also refer: Why saving changes to a database fails?
I'm working on a WPF MVVM Light application and I'd like to have a Boolean Method that uses a MYSql Query and C# to Progammatically determine if the Database exists. Any ideas would be greatly appreciated.
Maybe something with a query like :
SELECT IF(EXISTS (SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'Mark'), 'Yes','No')
Or:
SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'DBName'
I've got methods that will query the database but I'd like to have a checksum that determines if the db exists. If I use the code below it will error out so I'd like to determine first if the db exists and if it does query it.
static public Project.Project QueryProject(string projDatabaseName)
{
Project.Project proj = new Project.Project();
string connStr = "server=localhost;database=" + projDatabaseName + ";user=******;port=3306;password=********;";
string queryStr = "SELECT * FROM " + projDatabaseName + ".project";
MySqlConnection myConnection = new MySqlConnection(connStr);
MySqlCommand myCommand = new MySqlCommand(queryStr, myConnection);
myConnection.Open();
try
{
MySqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
proj.ProjectID = int.Parse(myReader["ProjectID"].ToString());
proj.ProjectName = myReader["ProjectName"].ToString();
proj.ProjectStartDate = Convert.ToDateTime(myReader["ProjectStartDate"]);
proj.ProjectEndDate = Convert.ToDateTime(myReader["ProjectEndDate"]);
proj.ProjectNotes = myReader["ProjectNotes"].ToString();
}
myReader.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return null;
}
finally
{
myConnection.Close();
}
return proj;
}
use INFORMATION_SCHEMA as the database the use show databases.
public bool DatabaseExists(string dbname)
{
string connStr = "server=localhost;database=INFORMATION_SCHEMA;";
using (MySqlConnection myConnection = new MySqlConnection(connStr))
{
string sql = "show databases";
MySqlCommand myCommand = new MySqlCommand(sql, myConnection);
myConnection.Open();
MySqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
string db = myReader["Database"].ToString();
if (db == dbname)
return true;
}
}
return false;
}
Try this:
SHOW DATABASES LIKE 'databaseName';
It returns an empty set if it doesn't exist.