SQL c# insert Command doesn't work - c#

I'm having a problem insertin data into my database.
I can read from the database by using the select query, so I know my connection string is correct, but for some reason the insert doesn't work.
Here's my code:
private string ConnectionString()
{
return #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\App_Data\dbBusiness.mdf;Integrated Security=True;User Instance=True";
}
private void Insert()
{
try{
string sqlStrInsert = "INSERT INTO myTable ([param1],[param2])VALUES(#param1,#param2)";
SqlConnection connection = new SqlConnection(ConnectionString());
SqlCommand command = new SqlCommand(sqlStrInsert, connection);
command.Parameters.Add("#param1", SqlDbType.SmallInt);
command.Parameters.Add("#param2", SqlDbType.NVarChar,50);
command.Parameters["#param1"].Value = numOf_company;
command.Parameters["#param2"].Value = txt_name.Text;
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
catch(Exception ex)
{
throw new Exception(ex.ToString(), ex);
}
}
It doesn't show any exeption, and when I check my table through the Visual studio explorer
nothing is added to the table.
Im having trouble figuring this out so
i'd appreciate anyone who helps

I believe you forgot your Initial Catalog in your connection. Because without it your code will try to run in master (the default database).
Here is a snippet that should help you, you will need to modify the code obviously for your benefit.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Working
{
class Program
{
static void Main(string[] args)
{
string DsQuery = "INSERT INTO table (param1,param2)VALUES(#param1,#param2)";
string TgtServer = #".\SQLEXPRESS";
DataSet dsServers = new DataSet();
dsServers = ExecQuery(DsQuery, TgtServer, "InitialCatalog");
}
private static DataSet ExecQuery(string strQuery, string strServer, string strIC)
{
string connectionString = #"Data Source=" + strServer + ";Initial Catalog=" + strIC + ";Integrated Security=SSPI";
string commandString = strQuery;
DataSet ds = new DataSet();
try
{
SqlDataAdapter da = new SqlDataAdapter(commandString, connectionString);
da.Fill(ds, "Table");
}
catch (SqlException e)
{
Console.WriteLine("An SQL Exception Occured: " + e.Message);
}
catch (Exception e)
{
Console.WriteLine("An General Exception Occured: " + e.Message);
}
return ds;
}
}
}
Sorry I can't give you anything more but that is something I noticed was missing and based on the no error given I can't provide.
Here is further reading:
http://technet.microsoft.com/en-us/library/aa905872(v=sql.80).aspx

Who is TABLE!?!? The name of your table? If yes, please change this name because if a reserved keyword
INSERT INTO table (param1,param2)VALUES(#param1,#param2)
becomes (for example)
INSERT INTO myTable (param1,param2)VALUES(#param1,#param2)

Related

C# odbc connection to sql creating tables but dont see in SQL Server

I want to create tables in SQL Server in my program. The code compiles and everything seems to be ok, but after I close it the tables don't appear in the SQL Server database.
EDITED
Please help here is the code and the connection string:
connectionString = "Driver={Sql Server}; Server=baxu\\sqlexpress; Database = baza1;" + $"UID ={ username };PWD={ password };";
Code:
try
{
using (OdbcCommand comm = new OdbcCommand())
{
comm.Connection = cnn;
comm.CommandText = cmdString;
comm.ExecuteNonQuery();
}
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.Message);
}
This here should work for you:
NB: If you dont use trusted connection - Then look at the different connectionstrings here:
var conn = new OdbcConnection();
conn.ConnectionString =
#"Driver={SQL Server};" +
#"Server=EGC25199\SQL2016;" +
#"DataBase=LegOgSpass;" +
#"Trusted_Connection=Yes;";
try
{
string cmdString = "CREATE TABLE dbo.odbctable (Wartosc int, Czas datetime)";
conn.Open();
using (OdbcCommand cmd = new OdbcCommand(cmdString, conn))
{
cmd.ExecuteNonQuery();
conn.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
This might help. I noticed you used an unassigned name in the create command.
using System;
using System.Data;
using System.Data.Odbc;
class CommandOdbcExample{
static void Main() {
OdbcConnection comm = new OdbcConnection(#"DSN=MyOdbcdDB");
OdbcCommand nonqueryCommand = comm.CreateCommand();
try {
comm.Open();
nonqueryCommand.CommandText = "CREATE TABLE MyTable (Wartosc int, Czas datetime)";
Console.WriteLine(nonqueryCommand.CommandText);
nonqueryCommand.ExecuteNonQuery();
}
catch (OdbcException ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
comm.Close();
Console.WriteLine("Connection Closed.");
}
}
}

Connecting to oracle Database wouldn't work

I want to connect to Oracle Database by visual studio and populate datagridview by its data. I know anything about Oracle . I just have SID,Username and password.
this is the code:
using Oracle.DataAccess.Client;
private void Form1_Load(object sender, EventArgs e)
{
var select = "SELECT * FROM tblProject";
conn.ConnectionString = "Data Source=(DESCRIPTION="
+ "(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=10.3.50.205)(PORT=1521)))"
+ "(CONNECT_DATA=(SERVER=DEDICATED)(SID=sid)));"
+ "User Id=username;Password=pass;";
}
using (OracleConnection connection = new OracleConnection(conn.ConnectionString))
{
OracleDataAdapter adapter = new OracleDataAdapter(select, connection);
try
{
connection.Open();
var ds = new DataSet();
adapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
but the connection wouldn't open? where is the problem?
Thank you
There are several DataConnectors on the market. At least from Microsoft, Oracle and DevArt. The connection strings are not fully compatible. So you have to pay attention when you are looking for examples.
I like to use ezconnect whenever it is possible:
username/password#[//]host[:port][/service_name]
less to type -> less errors. Once I had to connect to a test system which refused the old syntax, but accepted ezconnect. I never figured out why.
Can you try with the below code . Looks like you are using ODP.NET without the tnsnames.ora file using connect descriptor
using Oracle.DataAccess.Client;
private void Form1_Load(object sender, EventArgs e)
{
var select = "SELECT * FROM tblProject";
conn.ConnectionString = "Data Source=(DESCRIPTION="
+ "(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=10.3.50.205)(PORT=1521)))"
+ "(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=sid)));"
+ "User Id=username;Password=pass;";
using (OracleConnection connection = new OracleConnection(conn.ConnectionString))
{
connection.Open();
OracleDataAdapter adapter = new OracleDataAdapter(select, connection);
try
{
var ds = new DataSet();
adapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
check this documentation at the "Using the connect descriptor" section
https://docs.oracle.com/cd/B28359_01/win.111/b28375/featConnecting.htm

Connect a C# Windows Form App to a MySQL Database on a Linux based server

I am working on an C# application which would use the remote MySQL database located in my website hosted on a Linux server with PHP & MySQL support.
I tried to connect directly to the MySQL database using MySql.Data.MySQLClient Reference, as a result, my program is throwing following exception :
"Unable to connect to any of the specified MySQL hosts."
I searched many tutorials but got no solutions... getting the same error.
Can anybody please tell me how to do this.
Please suggest any online links or tutorials or your own idea.
Please help me.
here's my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace mysq
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
string conn = "Server = myserver;database = db ;uid = username ;password = pwd ;";
MySqlConnection con = new MySqlConnection(conn);
con.Open();
if (con.State == ConnectionState.Open)
{
MySqlCommand cmd = new MySqlCommand("Select * from table", con);
DataTable dt = new DataTable();
MySqlDataAdapter ad = new MySqlDataAdapter(cmd);
ad.Fill(dt);
dataGridView1.DataSource = dt;
}
}
catch (Exception)
{
throw;
}
}
}
}
Thanks in advance..
I've written an own class with functions for my mysql-connection.
First of all declare the server connection:
string ServerConnection = "Server=localhost;Port=1234;Database=YourDb;Uid=user;password=pass;"
This is how I select data:
public static void DB_Select(string s, params List<string>[] lists)
{
try
{
using(var conn = new MySqlConnection(ServerConnection))
{
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
string command = s;
cmd.CommandText = command;
using(var sqlreader = cmd.ExecuteReader())
while (sqlreader.Read())
{
if (sqlreader[0].ToString().Length > 0)
{
for (int i = 0; i < lists.Count(); i++)
{
lists[i].Add(sqlreader[i].ToString());
}
}
else
{
foreach (List<string> save in lists)
{
save.Add("/");
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error while selecting data from database!\nDetails: " + ex);
}
}
The call:
List<string> allRows = new List<string>();
DB_Select("SELECT field1 FROM table1 WHERE 1", allRows);
Notice: For every field you are selecting, you have to pass an own list which will be filled with the output.
For updating your database it would be quite the same function. You just wouldnt have to grad the output. Could look like this:
public static void DB_Update(string s)
{
try
{
using (var conn = new MySqlConnection(ServerConnection))
{
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
string command = s;
cmd.CommandText = command;
int numRowsUpdated = cmd.ExecuteNonQuery();
if(numRowsUpdated < 0)
{
MessageBox.Show("Warning DB-Contact: Affected_rows < 0!");
}
}
}
catch (Exception ex)
{
MessageBox.Show(String.Format("Updating database failed!\n\nSQL: {0}\n\nERROR: {1}",s,ex.Message));
}
}
You have to provide proper connection string in your program, i am suspecious you are passing proper IP address or hostname of the server where you hosted the database. As a first step try to ping the db server to make sure it is reachable from your machine. If it is reachable try as follows:
MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
string conn = "Server =<provide proper ip address >;database = db ;uid = username ;password = pwd ;";
conn = new MySql.Data.MySqlClient.MySqlConnection();
conn.ConnectionString = myConnectionString;
conn.Open();
More details here : http://dev.mysql.com/doc/connector-net/en/connector-net-programming-connecting-open.html

Connection to SQL Server Express from C#

I tried to open a connection with SQL Server Express and assign a new record on a specific table in C#.
This code is giving me this error
ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.
And the following:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
SqlConnection myConnection = new SqlConnection("Server=HABCHY-PC/SQLEXPRESS;" +
"Trusted_Connection=yes;" +
"Database=mydatabase;" +
"User Instance=true;"+
"Connection timeout=30");
try
{
myConnection.Open();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
SqlCommand myCommand = new SqlCommand("INSERT INTO students (firstname, age) "+
"Values ('string', 1)", myConnection);
myCommand.ExecuteNonQuery();
try
{
SqlDataReader myReader = null;
myCommand.CommandText = "select * from students";
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
Console.WriteLine(myReader["firstname"].ToString());
Console.WriteLine(myReader["age"].ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
try
{
myConnection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
Please tell me what's the problem.
I think this should work for you:
using System;
using System.Linq;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
public static SqlConnection GetConnectionsString()
{
return new SqlConnection("Server=HABCHY-PC\\SQLEXPRESS;" +
"Trusted_Connection=true;" +
"Database=mydatabase;" +
"User Instance=true;" +
"Connection timeout=30");
}
static void Main(string[] args)
{
using (SqlConnection myConnection = GetConnectionsString())
{
try
{
SqlCommand myCommand = new SqlCommand("INSERT INTO students (firstname, age) " + "Values ('string', 1)", myConnection);
Console.WriteLine("ee");
myConnection.Open();
myCommand.ExecuteNonQuery();
SqlDataReader myReader = null;
myCommand.CommandText = "select * from students";
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
Console.WriteLine(myReader["firstname"].ToString());
Console.WriteLine(myReader["age"].ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
}
As you can see I extracted the SQLConnection in another method.
This will help you when you want to make other database requests later.
With the using block you can make shure that your connection will be closed even if you got an exeption in your request.
Your mixing two approaches:
(1) either you have the database on the server and you access it via its logical database name (my preferred solution) - but in that case, you must not have a User Instance in your connection string - use this:
Server=HABCHY-PC\SQLEXPRESS;Database=mydatabase;Connection timeout=30;Integrated Security=SSPI;
( also note: the SQLEXPRESS instance name should be after a backslash - not a forward slash)
(2) or then you have the database as a on-disk .mdf file and it's not attached to the server (which is a messy and kludgy affair in my opinion). In that case, you have the User Instance, then then you need to specify the .mdf file as a file:
Server=HABCHY-PC\SQLEXPRESS;AttachDbFilename=C:\MyFolder\MyDataFile.mdf;User Instance=true;
Connection timeout=30;Integrated Security=SSPI;
May be your problem is here Trusted_Connection=yes; replace it with Trusted_Connection=True;.
if you are trying to use User Instance in connection string then you could use connection string like this
Data Source=.\SQLExpress;Integrated Security=true;
AttachDbFilename=C:\MyFolder\MyDataFile.mdf;User Instance=true;
you can get more connection string sample here
This will probably not be the answer to the question but I wrote this answer to help you write better code (not perfect probably :) ). I think you don't completely understand the concept of the use of a try-catch statement. There's not only try and catch but also the keyword finally. Everything in this statement will be executed, even when an exception is thrown. This way, you can handle the closing/disposing of variables if still needed, or execute other code that must be done, even when a exception is thrown.
static void Main(string[] args)
{
SqlConnection myConnection = new SqlConnection("Server=HABCHY-PC/SQLEXPRESS;" +
"Trusted_Connection=yes;" +
"Database=mydatabase;" +
"User Instance=true;"+
"Connection timeout=30");
SqlCommand myCommand = new SqlCommand("INSERT INTO students (firstname, age) "+
"Values ('string', 1)", myConnection);
try
{
myConnection.Open();
myCommand.ExecuteNonQuery();
myCommand.CommandText = "select * from students";
SqlDataReader myReader = myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
Console.WriteLine(myReader["firstname"].ToString());
Console.WriteLine(myReader["age"].ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
myReader.Close();
myConnection.Close();
}
}

C# SQL query returns nothing

I am trying to get my Winforms app to query a SQL Server CE database and return all rows that correspond to the column name specified by the user through a drop down list. When I run the programs it will return just a blank dataGrid. This is my first time working with SQL Server CE so any help would be appreciated.
My code is:
private void srchBTN_Click(object sender, EventArgs e)
{
string conString = Properties.Settings.Default.CurricularChangeTrackerConnectionString;
using (SqlCeConnection conn = new SqlCeConnection(conString))
{
string queryString = ("SELECT * FROM SecondaryEducation WHERE ProgramCode='" + PrgmCde.SelectedValue + "'");
try
{
conn.Open();
using (SqlCeDataAdapter adapter = new SqlCeDataAdapter(queryString, conn))
{
DataTable table = new DataTable();
adapter.Fill(table);
dataGridView1.DataSource = table;
adapter.Dispose();
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
If a property is not specified in ValueMember, SelectedValue returns the results of the ToString method of the object.
My point is you may not be getting what you think from the comboBox.
Try this:
string queryString = ("SELECT * FROM SecondaryEducation WHERE ProgramCode='" + PrgmCde.Items[PrgmCde.SelectedIndex].ToString() + "'");
You are declaring the data table inside the using statement, try this
private void srchBTN_Click(object sender, EventArgs e)
{
string conString = Properties.Settings.Default.CurricularChangeTrackerConnectionString;
DataTable table = new DataTable();
using (SqlCeConnection conn = new SqlCeConnection(conString))
{
string queryString = ("SELECT * FROM SecondaryEducation WHERE ProgramCode='" + PrgmCde.SelectedValue + "'");
try
{
conn.Open();
using (SqlCeDataAdapter adapter = new SqlCeDataAdapter(queryString, conn))
{
adapter.Fill(table);
dataGridView1.DataSource = table;
adapter.Dispose();
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
That way the table wont be disposed of when the scope of the using statement is ended.

Categories

Resources