Please i want to creat a Database if not exist, and after if the Database exist i want to creat tables.
I use this code :
using Npgsql;
string server = "localhost";
string database = "MyNewDatabase";
string password = "password1234";
string connectionString = #"Server=" + server + ";User Id=postgres; Password=" + password + ";";
var connection = new NpgsqlConnection(connectionString);
string commandText = string.Format("CREATE DATABASE IF NOT EXISTS \"{0}\";", database);
var command = new NpgsqlCommand(commandText);
connection.Open();
command.Connection = connection;
command.ExecuteNonQuery();
connection.Close();
the problem is i get a error : 42601 (syntax error using « NOT »).
Using C#, i am trying to verify if the database exist, if not we will creat it, and after we will verify if the tables exist, if they not exist we will creat them.
Please, may someone tell me how to do it?
Thanks stackoverflowers
Related
I wanted to insert some data to the mysql database using that ID that I have retrieved from datagridview. i am new in programming. can someone please help me? thanks
First you need to download and intall
MySQL ADO.Net connector
it's the official ado.net connector for C# applications. once you intall that you can use ado.net standered data access methods to save data.
basic steps
First create a connection to the my sql data base.
Then create a command object contains the insert command.
then provide the object that contain the so called ID and finalize the command object
then Execute the command against the database.
Sample code
This is the class variables that will be used later
private MySqlConnection connection; // this MySqlConnection class comes with the connector
private string server;
private string database;
private string uid;
private string password;
This will Initialize method will configure the connection with the configuration data
private void Initialize()
{
server = "localhost";
database = "connectcsharptomysql";
uid = "username";
password = "password";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
this method will open a connection to the database . you should write a C Lose method as well .because it's best practice to always close the connection after you used it
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
//When handling errors, you can your application's response based
//on the error number.
//The two most common error numbers when connecting are as follows:
//0: Cannot connect to server.
//1045: Invalid user name and/or password.
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}
This will insert a record to database . query will contains the T-SQL query that runs against the database
public void Insert()
{
string query = "INSERT INTO tableinfo (name, age) VALUES('John Smith', '33')";
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connection);
//Execute command
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
Hope this will help
i have a problem with making a local database into my c# project and creating it..
I tried first with making a Microsoft Sql Server but the problem is that i need to make app which should run on every pc. The app should input data from user , and collect it to the database, and on every start of program, the database should be filled with the leftover of earlier input.. What you suggest me to do?
First to connect your c# application with sqlite you should start with getting connection string
private static string executableLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
private static string oldconnectionstring = Path.Combine(executableLocation, "YourDB.db");
private static string connectionString = "Data Source =" + oldconnectionstring.ToString();
After getting connection, to add your input to database follow below steps
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
//Open connection to DB
conn.Open();
//Query to be fired
string sql = "Your Query to insert rows";
//Executing the query
using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
{
//Executing the query
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
//Close connection to DB
conn.Close();
}
I'm trying to update a CLOB column in my database with a long string containing the HTML contents of an email. There are 18,000 characters in the record I'm having an issue with.
The below code will work if I set the html variable to "short string". But if I try to run the code with the long 18,000 character HTML string, I get this error: "Oracle.DataAccess.Client.OracleException ORA-22922: nonexistent LOB value ORA-02063: preceding line from ((servername))"
public static void UpdateHtmlClob(string html, string taxId,string un, string pw)
{
using (OracleConnection conn = new OracleConnection())
{
try
{
conn.ConnectionString = "User Id=" + un + ";Password=" + pw + ";Data Source=server.com;";
conn.Open();
OracleCommand cmd = new OracleCommand();
string indata = html;
cmd.CommandText = "UPDATE table1 SET HTML_BODY = :clobparam";
OracleParameter clobparam = new OracleParameter("clobparam", OracleDbType.Clob, indata.Length);
clobparam.Direction = ParameterDirection.Input;
clobparam.Value = indata;
cmd.Parameters.Add(clobparam);
cmd.Connection = conn;
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
conn.Close();
}
}
}
Before you edited your code to reflect my answer, there were two problems with your code that I saw.
Firstly, you need to use a colon in your command text to tell Oracle that clobparam is a bind variable, not a column name:
cmd.CommandText = "UPDATE table1 SET HTML_BODY = :clobparam";
Secondly, you were not setting the database connection anywhere on the command. Which connection should the command be using? In your situation you have only one connection but more generally it may be possible to have more than one connection open. Add the line
cmd.Connection = connection;
or alternatively create the command using
OracleCommand cmd = connection.CreateCommand();
Of course, it would be nice if Oracle.DataAccess returned an error message that gave you the slightest hint that this was what you were doing wrong.
Anyway, now that you've edited your question to include the critical detail ORA-02063: preceding line from ((servername)), which tells us that you are using a database link, all I can really do is echo what I wrote in the comment: connect direct to the remote database to transfer LOB data, don't use a database link.
I am trying to connect to SQL Server 2012 express. There is a database called employee which I would like to save data from a WPF form to a table called [dbo].[EVUSERS]. It is stored in my local Database. From some examples I see that "Data Source=.\SQLEXPRESS" Is this correct? Or should I specify the table aswell? using localhost as the server doesn't work either.
I get an error saying "the server was not found or was not accessible."
Do I have to configure the server in some way to receive connections?
Here is my attempt.
void saveData()
{
try
{
var firstName = fNameTextbox.Text;
var lastName = LNameTextBox.Text;
var userName = UserName.Text;
String pass = PasswordTextBox.Password;
String confirm = ConfirmTextBox.Password;
int loggedIn = 1;
//parameterise values
string connectionString = #"Data Source=.\SQLEXPRESS;Database=Employee";
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO [dbo].[EVUSERS] (UName, Pass, FName, LName, Attempts, LastLogin, LoggedIn) VALUES (#UName, #Pass, #FName, #LName, #Attempts, #LastLogin, #LoggedIn)";
command.Parameters.AddWithValue("#UName", UserName);
command.Parameters.AddWithValue("#Pass", pass);
command.Parameters.AddWithValue("#FName", firstName);
command.Parameters.AddWithValue("#LName", lastName);
command.Parameters.AddWithValue("#Attempts", attempts);
command.Parameters.AddWithValue("#LastLogin", lastLogIn);
command.Parameters.AddWithValue("#LoggedIn", loggedIn);
connection.Open();
command.ExecuteNonQuery();
MessageBox.Show("command number of rows = " + command);
}
//connection.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
Here is a screenshot of the server connection.
Many Thanks
.\SQLExpress is correct. If the database name is correct (although for SQL Express it should be a path to the file, yes?) then you can add ";Integrated Security=SSPI" to the connection string and you'll be OK if you are the user who installed it.
Can Use It For Connect With Sql Server 2012 :
var connectionString = "Server=127.0.0.1;DataBase=Employee;
User Id=(sa or your user id without Parenthesis);
Password=(your password without Parenthesis);";
I have a piece of code that creates an SQL Server Express 2008 in runtime, and then tries to connect to it to execute a database initialization script in Transact-SQL. The code that creates the database is the following:
private void CreateDatabase()
{
using (var connection = new SqlConnection(
"Data Source=.\\sqlexpress;Initial Catalog=master;" +
"Integrated Security=true;User Instance=True;"))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText =
"CREATE DATABASE " + m_databaseFilename +
" ON PRIMARY (NAME=" + m_databaseFilename +
", FILENAME='" + this.m_basePath + m_databaseFilename + ".mdf')";
command.ExecuteNonQuery();
}
}
}
The database is created successfully. After that, I try to connect to the database to run the initialization script, by using the following code:
private void ExecuteQueryFromFile(string filename)
{
string queryContent = File.ReadAllText(m_filePath + filename);
this.m_connectionString = string.Format(
#"Server=.\SQLExpress; Integrated Security=true;Initial Catalog={0};", m_databaseFilename);
using (var connection = new SqlConnection(m_connectionString))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = queryContent;
command.CommandTimeout = 0;
command.ExecuteNonQuery();
}
}
}
However, the connection.Open() statement fails, throwing the following exception:
Cannot open database "TestData"
requested by the login. The login
failed. Login failed for user
'MYDOMAIN\myusername'.
I am completely puzzled by this error because the account I am trying to connect with has sysadmin privileges, which should allow me to connect any database (notice that I use a connection to the master database to create the database in the first place).
Is there a reason you specify User Instance=True when you create it but not when you try to connect to it?
When you create it after connecting with User Instance, it will create the database files but does not attach it to your actual instance. You'll either have to not specify User Instance=True in the first connection string or add it to the second and specify the database file to use.
Is the user you are logging with have rights to the database 'TestData'?
If not grant the user the privileges required.
I am not sure if this means anything, but in your first create you are connecting to server
.\\sqlexpress
The second one is
.\SQLExpress
You'll need to issue a CREATE USER command (see: http://msdn.microsoft.com/en-us/library/ms173463.aspx) after creating the database but before trying to open a connction to that database.
For example:
CREATE USER 'MYDOMAIN\myusername' FOR LOGIN 'MYDOMAIN\myusername'