Creating a database using Connector/NET Programming? - c#

How to create a database using connector/net programming? How come the following doesn't work?
string connStr = "server=localhost;user=root;port=3306;password=mysql;";
MySqlConnection conn = new MySqlConnection(connStr);
MySqlCommand cmd;
string s0;
try
{
conn.Open();
s0 = "CREATE DATABASE IF NOT EXISTS `hello`;";
cmd = new MySqlCommand(s0, conn);
conn.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}

You need to execute the command and also make sure to properly dispose objects:
string connStr = "server=localhost;user=root;port=3306;password=mysql;";
using (var conn = new MySqlConnection(connStr))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "CREATE DATABASE IF NOT EXISTS `hello`;";
cmd.ExecuteNonQuery();
}

You might want to execute the MySqlCommand. Now you just create one, but it doesn't execute your query.
Try this:
conn.Open();
s0 = "CREATE DATABASE IF NOT EXISTS `hello`;";
cmd = new MySqlCommand(s0, conn);
cmd.ExecuteNonQuery();
conn.Close();

execute your command and try this function
public void createDatabase(string server, string port, string database, string username, string password)
{
string connectionstring = string.Format("Server = {0}; Port ={1}; Uid = {2}; Pwd = {3}; pooling = true; Allow Zero Datetime = False; Min Pool Size = 0; Max Pool Size = 200; ", server, port, username, password);
using (var con = new MySqlConnection { ConnectionString = connectionstring })
{
using (var command = new MySqlCommand { Connection = con })
{
if (con.State == ConnectionState.Open)
con.Close();
try
{
con.Open();
}
catch (MySqlException ex)
{
msgErr(ex.Message + " connection error.");
return;
}
try
{
command.CommandText = #"CREATE DATABASE IF NOT EXISTS #database";
command.Parameters.AddWithValue("#database", database);
command.ExecuteNonQuery();//Execute your command
}
catch (MySqlException ex)
{
msgErr(ex.Message + " sql query error.");
return;
}
}
}
}

Imports MySql.Data.MySqlClient
Public Class Form1
Private dBf As String = "Empresa"
Private str As String = "Server = localhost; uid=root; pwd=;Database=mysql; pooling=false;"
Private Cmd As MySqlCommand
Private Con As New MySqlConnection(str)
Private Sub Form1_Load() Handles MyBase.Load
Try
Con.Open()
Cmd = New MySqlCommand("Create Database If Not exists " + dBf, Con)
Cmd.ExecuteNonQuery() : Con.ChangeDatabase(dBf)
Cmd = Con.CreateCommand
Cmd.CommandText = "CREATE TABLE Empleado" &
"(Id Char(10) COLLATE utf8_spanish_ci Not Null," &
"name VarChar(50) COLLATE utf8_spanish_ci Not Null," &
"email VarChar(50) COLLATE utf8_spanish_ci Not Null," &
"website VarChar(50) COLLATE utf8_spanish_ci Not Null," &
"Primary Key(id)) ENGINE=MyISAM"
Cmd.ExecuteNonQuery()
MsgBox("Registros, ok!!!") : Con.Close()
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Sub
End Class

Related

Load data Oracle Table to C# combobox using Oledb

hello i have create a table buy_unit in oracle database
CREATE TABLE buy_unit(
unit_id NUMBER(10) not null PRIMARY KEY,
unit_name VARCHAR2(10) not null
);
and insert Values
INSERT INTO BUY_UNIT
values(001,'Liter');
desc SELL_BUY_UNIT;
then create a combo box combobox1 in C# now can load buy_unit table data in combobox ? i have use the connection:
OleDbConnection con = new OleDbConnection("Provider=MSDAORA;Data Source=XE;User ID=user1;password=pssword");
Well, you can see below code which is refering SQLConnection. You can change as per your DB may be OracleConnection or so. While using SQL, we have pass connection string with UID and PWD.
For Oracle
have connection string as
string con = "Data Source=(DESCRIPTION =(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST = 000.00.0.00)(PORT = 0000)))(CONNECT_DATA =(SERVICE_NAME = database)));User ID=User/Schema;Password=password;Unicode=True";
public void BindComboBox()
{
SqlConnection con = new SqlConnection(#"server=ServerName; database = DBName ; User Id=sa; Password=PeaTeaCee5#");
con.Open();
string strCmd = "select desire column from table";
SqlCommand cmd = new SqlCommand(strCmd, con);
SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
DataSet ds = new DataSet();
da.Fill(ds);
cmd.ExecuteNonQuery();
con.Close();
cbSupportID.DisplayMember = "name to display";
cbSupportID.ValueMember = "id";
cbSupportID.DataSource = ds;
cbSupportID.Enabled = true;
}
and try to use using block when you open DB connection as below
using (OracleConnection objConn = new OracleConnection(con))
{
\\ you code
\\ do your stuff
}
Code for Oracle. Excuse for syntax.
public void Fillcombo()
{
string oradb = " Data Source=xe;User Id=dbname;Password=pws; ";
string query = "select id , name from table";
OracleConnection condatabase = new OracleConnection(oradb);
OracleCommand cmddatabase = new OracleCommand(query, condatabase);
try
{
condatabase.Open();
OracleDataReader myReader = cmddatabase.ExecuteReader(); ;
myReader = cmddatabase.ExecuteReader();
while (myReader.Read())
{
string sname = myReader.GetInt32(0).ToString();
comboBox1.Items.Add(sname.ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

How to Query Return Value on using Compact SQL Command?

I using a compact database created on visual studio. just for a stand alone system with it's database intact already although i'm stuck here in using a select query that could retrieve a boolean if the user exist on the database and also then return it's ID and Username if the user entry exist. can i ask for help regarding on this one.. I am a student trying to learn c# on using compact database.
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
if (!IsEmpty())
{
if (!IsLenght())
{
using (SqlCeConnection con = new SqlCeConnection("Data Source=" +
System.IO.Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "INCdb.sdf")))
{
con.Open();
SqlCeCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT * FROM LoginTB Where username=#user1 AND password=#pass1";
cmd.Parameters.AddWithValue("#user1", UserTxt.Text.Trim());
cmd.Parameters.AddWithValue("#pass1", PassTxt.Text.Trim());
cmd.CommandType = CommandType.Text;
validlogin = (bool)cmd.ExecuteScalar();
con.Close();
MessageBox.Show(validlogin.ToString());
if (validlogin == true)
{
// cmd. return value ID
// cmd. return value Username
//SysMain Mn = new SysMain();
//Mn.ShowDialog();
//this.Hide();
}
}
}
}
}
catch (Exception ex)
{
gbf.msgBox(1, ex.Message.ToString(), "");
}
}
The code below is probably better, unless there is something special and unstated about the schema of LoginTB.
// ...
var validLogin = false;
using (SqlCeConnection con = new SqlCeConnection(
"Data Source=" +
System.IO.Path.Combine(
Path.GetDirectoryName(
System.Reflection.Assembly.GetEntryAssembly().Location),
"INCdb.sdf")))
{
con.Open();
SqlCeCommand cmd = con.CreateCommand();
cmd.CommandText =
"SELECT COUNT(*) FROM LoginTB Where username=#user1 AND password=#pass1";
cmd.Parameters.AddWithValue("#user1", UserTxt.Text.Trim());
cmd.Parameters.AddWithValue("#pass1", PassTxt.Text.Trim());
cmd.CommandType = CommandType.Text;
validlogin = ((int)cmd.ExecuteScalar()) > 0;
}
MessageBox.Show(validlogin.ToString());
// ...
Note the use of COUNT

Connect to SQL Server in C#

I'm a beginner programmer with C#. I'm trying to develop an application that it connects to a database and do the typical operations like insert, delete, update and get.
I'm getting a error with the database connection. I'm working with SQL Server 2012, where I have create a database called company.
This is my code:
namespace DAL
{
public class DAL
{
public const string CADENA_CONEXION = "Data Source=localhost;" +
"Initial Catalog=Company" +
"Integrated Security=false" +
"UID=root PWD=root";
public SqlConnection con;
public SqlCommand command;
public DAL()
{
con = new SqlConnection();
con.ConnectionString = CADENA_CONEXION;
}
public Boolean addEmployee(Employee emp)
{
try
{
/*String sqlInsertString = "INSERT INTO Employee (FirstName, LastName, ID, " +
"Designation) VALUES ("+e.firstName+","+ e.lastName+","+e.empCode+","+e.designation+")";*/
string sqlInsertString =
"INSERT INTO Employee (FirstName, LastName, ID, " +
"Designation) VALUES (#firstName, #lastName, #ID, #designation)";
command = new SqlCommand();
command.Connection.Open();
command.CommandText = sqlInsertString;
SqlParameter firstNameparam = new SqlParameter("#firstName", emp.FirstName);
SqlParameter lastNameparam = new SqlParameter("#lastName", emp.LastName);
SqlParameter IDparam = new SqlParameter("#ID", emp.EmpCode);
SqlParameter designationParam = new SqlParameter("#designation", emp.Designation);
command.Parameters.AddRange(new SqlParameter[]{
firstNameparam,lastNameparam,IDparam,designationParam});
command.ExecuteNonQuery();
command.Connection.Close();
return true;
}
catch (Exception ex)
{
return false;
throw;
}
return true;
}
}
What is the error? I get an exception on this line:
command.Connection.Open();
Thanks in advance
SqlConnection con = new SqlConnection("Your Connection String Goes here");
You should assign connection to SqlCommand object like this
SqlCommand command = new SqlCommand();
command.Connection = con;
or
SqlCommand command = new SqlCommand("YourQuery",con);
Some Important Steps to Execute Command
1: Create SqlConnection Object and Assign a connection string to that object
SqlConnection con = new SqlConnection("Your Connection String Goes here");
or
SqlConnection con = new SqlConnection();
con.Connection = "Your Connection String Goes here";
2: Create SqlCommand Object and assing a command Text(Your Query) and connection string to that object
SqlCommand command = new SqlCommand("Select * from Products",con);
or
SqlCommand command = new SqlCommand();
command.Connection = con;
command.CommandText ="Select * from Products";
You can also specify CommandType
command.CommandType =CommandType.Text;
/* if you are executing storedprocedure CommandType Will be
=> CommandType.StoredProcedure; */
then You can Execute Command Like this
try
{
con.Open();
int TotalRowsAffected = command.ExecuteNonQuery();
}
catch(Exeception ex)
{
MessageBox.Show(ex.Message);
}
finaly
{
con.Close();
}
Just an FYI: An alternative to the try finally blocks, which ensure the database connection gets closed is to use the using statement such as:
using (SqlConnection connection = new SqlConnection(
connectionString))
{
try
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
catch (InvalidOperationException)
{
//log and/or rethrow or ignore
}
catch (SqlException)
{
//log and/or rethrow or ignore
}
catch (ArgumentException)
{
//log and/or rethrow or ignore
}
}
Refer to the MSDN documentation for the SqlCommand class here, https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx, and look up the ExecuteNonQuery() method, which is used to execute INSERT, UPDATE, and DELETE statements. Then look up ExecuteScalar() method that you can use to execute SELECT statements that return a single value. You can use ExecuteReader() to return a SqlDataReader for SELECT statements that return multiple columns.
not initialize sqlcommand connections, way for initialize this is :
command.Connection=con;
this is complete code for you :
namespace DAL
{
public class DAL
{
public const string CADENA_CONEXION = "Data Source=localhost;" +
"Initial Catalog=Company" +
"Integrated Security=false" +
"UID=root PWD=root";
public SqlConnection con;
public SqlCommand command;
public DAL()
{
con = new SqlConnection();
con.ConnectionString = CADENA_CONEXION;
}
public Boolean addEmployee(Employee emp)
{
try
{
/*String sqlInsertString = "INSERT INTO Employee (FirstName, LastName, ID, " +
"Designation) VALUES ("+e.firstName+","+ e.lastName+","+e.empCode+","+e.designation+")";*/
string sqlInsertString =
"INSERT INTO Employee (FirstName, LastName, ID, " +
"Designation) VALUES (#firstName, #lastName, #ID, #designation)";
command = new SqlCommand();
command.Connection=con;
command.Connection.Open();
command.CommandText = sqlInsertString;
SqlParameter firstNameparam = new SqlParameter("#firstName", emp.FirstName);
SqlParameter lastNameparam = new SqlParameter("#lastName", emp.LastName);
SqlParameter IDparam = new SqlParameter("#ID", emp.EmpCode);
SqlParameter designationParam = new SqlParameter("#designation", emp.Designation);
command.Parameters.AddRange(new SqlParameter[]{
firstNameparam,lastNameparam,IDparam,designationParam});
command.ExecuteNonQuery();
command.Connection.Close();
return true;
}
catch (Exception ex)
{
return false;
throw;
}
return true;
}
}

update a mySQL table using C#

I have written some C# to update a MySql table but I get an exception every time I call the method ExecuteNonQuery(). I have researched this on the web and every solution I find produces the same error. I have an open connection to the database and the update query to the database is written correctly. The code that I have so far come up with is :
public int executeUpdate()
{
int result = 0;
if (isConnected)
{
try
{
MySqlConnection cn = new MySqlConnection(connection.ConnectionString);
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = cn;
cmd.CommandText = "UPDATE test SET status_id = 1 WHERE test_id = 1";
int numRowsUpdated = cmd.ExecuteNonQuery();
}
catch (MySqlException exSql)
{
Console.Error.WriteLine("Error - SafeMySql: SQL Exception: " + query);
Console.Error.WriteLine(exSql.StackTrace);
}
catch (Exception ex)
{
Console.Error.WriteLine("Error - SafeMySql: Exception: " + query);
Console.Error.WriteLine(ex.StackTrace);
}
}
else
Console.Error.WriteLine("Error - SafeMySql: executeQuery failed. Not connected to DB");
}
Change your try section to the code below:
try
{
using(MySqlConnection cn = new MySqlConnection(connection.ConnectionString))
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = cn;
cmd.CommandText = "UPDATE test SET status_id = 1 WHERE test_id = 1";
cn.Open();
int numRowsUpdated = cmd.ExecuteNonQuery();
cmd.Dispose();
}
}
The connection must be opened before you execute a command. In the example above the command object will immediately be disposed and the connection object will implcitly be closed and disposed when you leave the using section.
I don't see the connection being opened.
Here is an example from MSDN: even inside a using block, they open the connection explicitly
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
Edit: The principle is the same for MySQL as it is for SQL Server:
public void CreateMySqlCommand(string myExecuteQuery, MySqlConnection myConnection)
{
MySqlCommand myCommand = new MySqlCommand(myExecuteQuery, myConnection);
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}

My whole delete method() is executing successfully and there is no error,but the records are not being deleted

When debugger is applied the query-line shows no data in textBox1.Text.my code is following:
namespace SeparateConnection
{
class clsGridView
{
Connection co2 = new Connection();
//display our global varaible for connection
SqlConnection myconn3 = new SqlConnection("data source=M-SULEMAN-PC;initial catalog=dbmsLogin;integrated security=sspi");
public void Delete()
{
co2.setconn();
try
{
DialogResult result = MessageBox.Show("Are you sure you want to delete ?", "Message",
MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
//myconn3.Open();
DataTable table2 = new DataTable();
frmGridView gd = new frmGridView();
SqlDataAdapter myadd2 = new SqlDataAdapter("Delete from tblLogin where UserName ='" + gd.textBox1.Text + "'", myconn3);
myadd2.Fill(table2);
//Sqlcommandbulider to allow changes to database
SqlCommandBuilder mybuild = new SqlCommandBuilder(myadd2);
//Update the database
myadd2.Update(table2);
//Close the connection
myconn3.Close();
}
else
return;
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
----------when I use the same class for calling and defining the method..there is no problem
To delete data you must follow this pattern:
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Delete from tblLogin where UserName = #param";
cmd.Parameters.Add("#param", gd.textBox1.Text);
cmd.Connection = conn;
cmd.ExecuteNonQuery();
why dont you try out something like this
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter = new SqlDataAdapter();
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
connection = new SqlConnection(connetionString);
sql = "delete product where Product_name ='Product6'";
try
{
connection.Open();
adapter.DeleteCommand = connection.CreateCommand();
adapter.DeleteCommand.CommandText = sql;
adapter.DeleteCommand.ExecuteNonQuery();
MessageBox.Show ("Row(s) deleted !! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}

Categories

Resources