I'm trying to INSERT data into my SQL database but its not showing anything at all.
This is a for an online role-playing game . There is no error but when I refresh my browser for phpmyadmin using XAMP, no data is being shown.
MySqlConnection connection = new MySqlConnection(connectionString);
connection.Open();
string checkDatabase = "select * from players where username = #playerName";
MySqlCommand command = new MySqlCommand(checkDatabase, connection);
command.Parameters.AddWithValue("#playerName", player.SocialClubName);
MySqlDataReader reader = command.ExecuteReader();
if(reader.Read())
{
player.SendChatMessage("There is an account with the assiociated Social Club Profile!");
}
else
{
MySqlConnection connection1 = new MySqlConnection(connectionString);
connection1.Open();
string playerInsert = "insert into players(username,password) VALUES (#user,#password)";
MySqlCommand command1 = new MySqlCommand(playerInsert, connection1);
command1.Parameters.AddWithValue("#user", player.SocialClubName);
command1.Parameters.AddWithValue("#password", password);
connection1.Close();
}
connection.Close();
You need to execute the query. Try:
...
command1.ExecuteNonQuery();
That's cause you are not executing the query at all as can be seen in below posted code
string playerInsert = "insert into players(username,password) VALUES (#user,#password)";
MySqlCommand command1 = new MySqlCommand(playerInsert, connection1);
command1.Parameters.AddWithValue("#user", player.SocialClubName);
command1.Parameters.AddWithValue("#password", password);
command1.ExecuteNonQuery(); //execute the query
connection1.Close();
Related
I am trying to update username from MVC .Net C# after connecting Postgres SQL.
I am able to establish the connection and if I run select command I am able to get the result.
But when I am trying to update record no error comes but updated count comes 0. Record available in database.
Can you please suggest what could be the reason.
using (NpgsqlConnection con = new NpgsqlConnection(connectionString))
{
string query = string.Format("UPDATE um_user SET um_user_name='{0}' WHERE um_user_name='{1}'", updatedUser, userNameToBeUpdated);
con.Open();
NpgsqlCommand comn = new NpgsqlCommand(query, con);
comn.Connection = con;
updatedRows = comn.ExecuteNonQuery();
comn.Dispose();
con.Close();
}
I have added using parameter as well with the following code but still getting 0 updtaed rows.
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
NpgsqlCommand cmd = new NpgsqlCommand();
cmd.Connection = connection;
cmd.CommandText = "update um_user set um_user_name=#newName where um_user_name=#oldName";
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new NpgsqlParameter("#newName", updatedUser));
cmd.Parameters.Add(new NpgsqlParameter("#oldName", userNameToBeUpdated));
updatedRows = cmd.ExecuteNonQuery();
cmd.Dispose();
connection.Close();
}
For reference, this page (add.ashx.cs), is an add page to a database.
What I'm trying to do is :
figure out how to execute string queryID, and then
store the results of queryID
I'm a bit new at this, but this is what I'm working with so far. Am I on the right path, and what should I change? I don't believe the code below includes storing the results, but just executing queryID.
// new query to get last ID value
// store the command.executeNonQuery results into a variable
string queryID = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
// first: look up how to execute queryID
// then: store results of query ^
// execute queryID? (section below)
SqlConnection sqlConnection1 = new SqlConnection(queryID);
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "Select * FROM queryID";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
// data is accessible through the datareader object here
sqlConnection1.Close();
There are some things missmatched in your code sample. First queryID is your actual query. Second in SqlConnection you need to provide a connection string, that connects to your database (SQL Server, ACCESS, ...). A valid example could look like this:
// this is just a sample. You need to adjust it to your needs
string connectionStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=SSPI;";
SqlConnection sqlConnection1 = new SqlConnection(connectionStr);
SqlCommand cmd = new SqlCommand(sqlConnection1 );
SqlDataReader reader;
cmd.CommandText = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
cmd.CommandType = CommandType.Text;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
List<string> results = new List<string>();
if(reader.HasRows)
{
while(reader.Read())
{
results.Add(reader[0].ToString());
}
}
sqlConnection1.Close();
Another thing is, that you execute a reader but only select one single value. You can perfectly use ExecuteScalar for that:
// this is just a sample. You need to adjust it to your needs
string connectionStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=SSPI;";
SqlConnection sqlConnection1 = new SqlConnection(connectionStr);
SqlCommand cmd = new SqlCommand(sqlConnection1 );
cmd.CommandText = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
cmd.CommandType = CommandType.Text;
sqlConnection1.Open();
string result = cmd.ExecuteScalar().ToString();
sqlConnection1.Close();
One last thing. You should use objects that implement IDisposable in a using block. This way the will be removed from memory when they are no longer needed:
// this is just a sample. You need to adjust it to your needs
string connectionStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=SSPI;";
using(SqlConnection sqlConnection1 = new SqlConnection(connectionStr))
{
SqlCommand cmd = new SqlCommand(sqlConnection1 );
cmd.CommandText = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
cmd.CommandType = CommandType.Text;
sqlConnection1.Open();
string result = cmd.ExecuteScalar().ToString();
}
I am fully new in the programming section so don't try bad help pls.
Actually I am fail focus data from phpmyadmin to c# windows form textbox1.Text area.
My database name: business, Table Name: life, columns Name : Email_id
I need to show email id 10 number row in my textbox1.Text area.
See my code
string connString = "datasource=x5x.1x1.13x.xxx;Database=business;username=sumon;password=root";
MySqlConnection connect = new MySqlConnection(connString);
MySqlCommand myCommand = connect.CreateCommand();
string input = textBox1.Text;
myCommand.CommandText = "SELECT * FROM life WHERE id = #input";
connect.Open();
MySqlDataReader reader = myCommand.ExecuteReader();
if (reader.Read())
textBox1.Text = reader["*"].ToString();
connect.Close();
you've missed to set the value for #input. I edited you code (without testing). Give it a try.
string connString = "datasource=x5x.1x1.13x.xxx;Database=business;username=sumon;password=root";
MySqlConnection connect = new MySqlConnection(connString);
MySqlCommand myCommand = connect.CreateCommand();
myCommand.Parameters.Add(new SqlParameter("input", 10));
//string input = textBox1.Text;
myCommand.CommandText = "SELECT * FROM life WHERE id = #input";
connect.Open();
MySqlDataReader reader = myCommand.ExecuteReader();
if (reader.Read())
textBox1.Text = reader["Email_id"].ToString();
connect.Close();
I am currently trying to populate a listview with some data I have pulled from my database table; but not sure where to start; I have tried the following:
lstData.DataSource = conn;
lstData.DataBind();
But that causes an error:
"Data source is an invalid type. It must be either an IListSource,
IEnumerable, or IDataSource. MVC"
Am I using the correct query strings in order to populate my listview?
Thanks,
Callum
C# Code:
string ssConnectionString = "Server connection";
SqlConnection conn = new SqlConnection(ssConnectionString);
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT Category FROM [dbo].[Category] WHERE CategoryID = '16'";
command.ExecuteNonQuery();
string com = command.ExecuteScalar().ToString();
lblSQL.Text = com;
conn.Close();
Using your code as a base to start from you may want to try the following: I assume your connection in "Server connection" is a place holder for a real connection string and you know what should go there.
string ssConnectionString = "Server connection";
SqlConnection conn = new SqlConnection(ssConnectionString);
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT Category FROM [dbo].[Category] WHERE CategoryID = '16'";
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dataTable;
da.Fill(dataTable);
lstData.DataSource = dataTable;
lstData.DataBind();
conn.Close();
I've seen this question asked a couple times but I couldn't find a good answer. I've been stuck for hours on this.
Basically I have usernames saved in a database and when a new user registers I want to check if his username is available - and if it is available add him to the database. And they register through a textbox called FName. The table is called Users.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT FName FROM Users WHERE FName = ????? usernames????? ", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader["text"].ToString());
}
How can I fix this code?
"SELECT FName FROM Users WHERE FName = #paramUsername"
and then you insert the parameter into the cmd like so:
cmd.Parameters.Add("paramUsername", System.Data.SqlDbType.VarChar);
cmd.Parameters["paramUsername"].Value = "Theusernameyouarelookingfor";
Check this out:
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string validationQuery = "SELECT * FROM Users WHERE FName = #name";
SqlCommand validationCommand = new SqlCommand(validationQuery, connection);
validationCommand.Parameters.Add("#name", SqlDbType.VarChar).Value = loginUserSelected;
connection.Open();
SqlDataReader validationReader = validationCommand.ExecuteReader(CommandBehavior.CloseConnection);
if (!validationReader.Read())
{
string insertQuery = "INSERT INTO Users (FName) VALUES (#name)";
SqlCommand insertCommand = new SqlCommand(insertQuery, connection);
insertCommand.Parameters.Add("#name", SqlDbType.VarChar).Value = loginUserSelected;
connection.Open();
insertCommand.ExecuteNonQuery();
insertCommand.Dispose();
connection.Close();
}
else
{
//Uh oh, username already taken
}
validationReader.Close();
validationCommand.Dispose();
Things to note:
Use parameters, avoid concatenating strings because it's a security vulnerability
Always Close and Dispose your ADO objects