How to connect to SQL Server CE using ADO.NET - c#

I have a EntityModel created from ADO.NET that connects to my database. I want to fill a DataGridview. For that I'm following this code:
using System.Data;
using System.Data.SqlServerCe;
using System.Windows.Forms;
namespace WindowsFormsApplication5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
FillData();
}
void FillData()
{
// 1
// Open connection
using (SqlCeConnection c = new SqlCeConnection(
Properties.Settings.Default.DataConnectionString))
{
c.Open();
// 2
// Create new DataAdapter
using (SqlCeDataAdapter a = new SqlCeDataAdapter(
"SELECT * FROM Animals", c))
{
// 3
// Use DataAdapter to fill DataTable
DataTable t = new DataTable();
a.Fill(t);
// 4
// Render data onto the screen
dataGridView1.DataSource = t;
}
}
}
}
This code comes from a Web Page, so I'm trying to adapt it to my ADO.NET model. So, as I'm not sure where the Properties.Settings.Default.DataConnectionStringcomes from, I thought it was the connection string used to connect to my database, so, following my Entity Model, I wrote this to get the connection string:
SqlCeConnection c = new SqlCeConnection(db.Connection.ConnectionString);
Where db is my Entity Model created like this:
private dbEntities db = new dbEntities();
But this db.Connection.ConnectionString returns this: "name= dbEntities", so I changed it to db.Connection.DataSource, that returns this string:
"C:\\Users\\user\\Documents\\Visual Studio 2010\\Projects\\ProjectName\\MySQLProject\\bin\\Debug\\db.sdf" string
But it says that the string format is not adjusted (obviously...). I'm using SQL Server, but I'm not sure how to get that connection :(
The Properties.Settings.Default.DataConnectionString says this:
Properties.Settings.Default.dbConnectionString 'System.Windows.Forms.PropertyStore'
does not contain a definition for 'Settings' and no extension method 'Settings' accepting a first argument of type 'System.Windows.Forms.PropertyStore' could be found (are you missing a using directive or an assembly reference?)

The message does not mean the connection string is in wrong format! Is says that there are no settings in your project.
Are you sure that you created a respective setting? To edit them, double click the "Properties" entry in your project, then switch to the "Settings" tab. If there's no entry dbConnectionString, create one.

Related

MySQL connection to a win form app in visual studio 2019

I can't get the form design to work my project compiles perfectly, but when I try to get click my button the file say key word not supported "allowloadlocalinfile"
I copied and paste what i thought was the connection string
server=localhost;userid=root;database=resume;persistsecurityinfo=True;allowloadlocalinfile=False;sslmode=None
but i get this error
here is my interface code
using System;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Windows.Forms;
namespace Resume2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server=localhost;userid=root;database=resume;persistsecurityinfo=True;allowloadlocalinfile=False;sslmode=None");
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO fields VALUES (#ResumeF_Name,#ResumeL_Name)",
con);
cmd.Parameters.AddWithValue("#ResumeF_Name", textBox1.Text);
cmd.Parameters.AddWithValue("#ResumeL_Name", textBox2.Text);
cmd.ExecuteNonQuery();
con.Close();
}
}
}
I leave out the id column because it is set to auto_increment but he other to columns in my MySQL database "resume" table "fields" are ResumeF_Name and Resume_L_Name
now it's saying the connection string is server=localhost;user id=root;database=resume but still have a popup error
You have to use a connectionString for MySql instead of MS SQL.
Here are the main steps:
You have to add the nuget package "MySql.Data" to your project
Then you have to add the using using MySql.Data.MySqlClient(); to your code
You can then use this MySqlConnection cnn = new MySqlConnection("Server=localhost;Database=resume;Uid=root;Pwd=yourPassword;");
If you need some information about the connectionString for MySql. You can find out more information at this website: https://www.connectionstrings.com/mysql-connector-net-mysqlconnection/

C# variable in a MySql query isn't recognized

I have an int variable in my C# code and I'm trying to use it in a MySql query.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace projeV1
{
public partial class ProjeDetay : Form
{
public ProjeDetay()
{
InitializeComponent();
}
private void ProjeDetay_Load(object sender, EventArgs e)
{
int satir_projem = Projeler.satir_proje;
string connectionString = "Server = localhost; Port = ...; Database = ...; Uid = root; Pwd = ...; Allow User Variables=True";
MySqlConnection databaseConnection = new MySqlConnection(connectionString);
MySqlCommand command;
databaseConnection.Open();
command = databaseConnection.CreateCommand();
string myQuery = "select projeAdi from projeler where projeID = #satir_projem";
MySqlDataAdapter dataAdapter = new MySqlDataAdapter(myQuery, databaseConnection);
command.Parameters.Add("#satir_projem", MySqlDbType.Int32).Value = satir_projem;
DataSet DS = new DataSet();
dataAdapter.Fill(DS);
dataGridView_ProjeDetay.DataSource = DS.Tables[0];
MessageBox.Show(Projeler.satir_proje.ToString());
MessageBox.Show(satir_projem.ToString());
}
}
}
(Sorry if it looks like a mess in regard to coding but I'm new at this ^^)
MessageBox windows show the variables' values correctly, so there's no problem with the variable. And when I replace#satir_projem from the query string with a number like "2" (see the example below), for example, the result is correct, but when I use #satir_projem in the query, it doesn't work. I can't see what I'm doing wrong.
Example query string:
"select projeAdi from projeler where projeID = 2"
P.S 1: Originally I'm trying to get the index of the selected row (which is the variable called Projeler.satir_proje) in a DataGridView used in a form called "Projeler" and in another form (which is called ProjeDetay), assigning that index value into another variable called "satir_projem" and use this value to get the related data from my database and put that data in another DataGridView located in my second form (which is called dataGridView_ProjeDetay).
P.S 2: I've made a lot of research about this problem and tried many of the solutions I encountered along the way; however, none of them worked for me. So, here I am :)
Thanks in advance.
You are setting parameter for command that is not used.
Instead you should use DataAdapter.SelectCommand
dataAdapter.SelectCommand.Parameters.Add(...)
MySqlConnection databaseConnection = new MySqlConnection(connectionString);
MySqlCommand command;
string myQuery = "select projeAdi from projeler where projeID = #satir_projem";
databaseConnection.Open();
command = new MySqlCommand(myQuery, databaseConnection);
MySqlDataAdapter dataAdapter = new MySqlDataAdapter(command);
Just want to elaborate, why #Onur_Saatcioglu's code is throwing error.
you are adding #satir_projem to command but the parameter thus added to command is not being passed to dataadapter which serves as a bridge between a DataSet and SQL Server for retrieving and saving data.
Hence you can
1) As Lester told, create command like
command = new MySqlCommand(myQuery, databaseConnection);
and pass the command to DataAdapter
MySqlDataAdapter dataAdapter = new MySqlDataAdapter(command);
2) As #Pablo_notPicasso said, if you are using
dataAdapter.SelectCommand.Parameters.AddWithValue("#satir_projem", satir_projem);
then "command" does not make sense, you can just delete it.

C# Error Selecting Table in OleDbCommand ...*LIBL not found

I'm trying to make a connection to a DB2 Database sitting on our AS400 (ISeries). I can connect to is successfully using the connection string but once I try to access the Tables I get this error: CPF9812: File SELECT in library *LIBL not found.
At this point I'm just trying to see if i can access the data in the table GLPCT.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Data;
namespace Testing_Connection_to_GLDBFA
{
class Program
{
static void Main(string[] args)
{
string connectionstring = "Provider=IBMDARLA.DataSource.1;Data Source=INFINIUM;Persist Security Info=True;Password=MyPassword;User ID=UserID;Initial Catalog=S06947A4;Default Collection=GLDBFA";
string querySTring = "";
DataTable schema;
int i = 0;
using( OleDbConnection cn = new OleDbConnection(connectionstring))
{
querySTring = "SELECT * FROM GLPCT";
OleDbCommand command = new OleDbCommand(querySTring, cn);
cn.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader[0].ToString());
i++;
if (i == 20)
break;
}
cn.Close();
}
}
}
}
Any help or guidance is greatly appreciated.
Thanks in advance.
I'd expect to see the following error:
CPF9812: File GLPCT in library USERID not found.
As by default when using SQL naming the system will implicitly qualify unqualified table names with the user ID. For details, see here
It appears you are using an OLE DB provider instead of the .NET provider
If you want to use the library list, you'll need use system naming and ensure that the library list is configured on the connection.
For the OLEDB providers, you want to set the Library List and Naming Convention
<connection>.Open('Provider=IBMDA400;Data Source=SystemA;Library List=lib1,lib2, *USRLIBL;Naming Convention=1', 'Userid', 'Password');
For .NET provider, it's LibraryList and Naming properties.
Lastly, if you want to stay with the OLE DB provider, you might consider using the IBMDASQL instead of the IBMDARLA one.

Retrieving Data From a data source and displaying in a GridView

I am having problems getting data to be displayed in a gridview in VS 2010.
I have a SQLdataSource which is connecting to my database but the gridview is not showing at all, my error message is all that is displayed. Would anyone know why this is?
This is the code that I have:
`using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Web.Services.Description;
namespace DBprototype2
{
public partial class _Default : System.Web.UI.Page
{
void Page_Load(Object sender, EventArgs e)
{
// This example uses Microsoft SQL Server and connects
// to the Northwind sample database. The data source needs
// to be bound to the GridView control only when the
// page is first loaded. Thereafter, the values are
// stored in view state.
if(!IsPostBack)
{
// Declare the query string.
String queryString =
"SELECT * FROM ";
// Run the query and bind the resulting DataSet
// to the GridView control.
DataSet ds = GetData(queryString);
if (ds.Tables.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
Label1.Text = "Connected.";
}
else
{
Label1.Text = "Unable to connect to the database.";
}
}
}
DataSet GetData(String queryString)
{
// Retrieve the connection string stored in the Web.config file.
String connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
DataSet ds = new DataSet();
try
{
// Connect to the database and run the query.
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);
// Fill the DataSet.
adapter.Fill(ds);
Label1.Text = "Connected.";
}
catch(Exception ex)
{
// The connection failed. Display an error message.
Label1.Text = "Unable to connect.";
}
return ds;
}
}
}
`
If anyone could tell me the problem with my code that would be extremely helpful.
The problem is your query:
String queryString =
"SELECT * FROM ";
You are missing the table to select from, later in your method GetData you are not adding any table name in the query, that is why it is failing.
Also consider enclosing your connection in using statement
Use the Exception object ex.Message instead of hard coded error in label, this will help you debug and see what exactly is going wrong.
Not for this particular scenario but always consider using parametrized queries.

Calling class from code behind

I am still new to ASP.net and I'm learning how to call classes. I've looked around for tutorials, but not all are specific to ASP.net 4.0 so I'm not sure if I should apply them.
Right now, I am trying to connect to my SQL database. My webconfig file has been set up with the connectionstring "dbConnectionString" and is working properly when I've tested it with GridViews. What I'd like to do now is access the database from code behind.
I've seen some ways to accomplish this, but I'd like the most efficient, resuable way. I've tried to adopt the answer listed here: How to create sql connection with c# code behind, access the sql server then conditionally redirect? however, I'm getting an error.
I am doing this with C# as a website, not a web application. Here is my code behind for Login.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SqlComm; // Is this how I connect to my class from this page????
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//no code written yet
}
}
}
My class in the App_Code folder, file name SQLComm.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web;
/// <summary>
/// SQL Query class
/// </summary>
public class SqlComm
{
// Connection string
static string DatabaseConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["dbConnectionString"].ConnectionString;
// Execute sql command with no value to return
public static void SqlExecute(string sql)
{
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
// Execute SQL query and return a value
public static object SqlReturn(string sql)
{
using (SqlConnection conn = new SqlConnection(PjSql.dbcs()))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
object result = (object)cmd.ExecuteScalar();
return result;
}
}
// Retrieve an entire table or part of it
public static DataTable SqlDataTable(string sql)
{
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Connection.Open();
DataTable TempTable = new DataTable();
TempTable.Load(cmd.ExecuteReader());
return TempTable;
}
}
// Execute a stored procedure with 1 parameter
// Returning a value or just executing with no returns
public static object SqlStoredProcedure1Param(string StoredProcedure, string PrmName1, object Param1)
{
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
SqlCommand cmd = new SqlCommand(StoredProcedure, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter(PrmName1, Param1.ToString()));
cmd.Connection.Open();
object obj = new object();
obj = cmd.ExecuteScalar();
return obj;
}
}
}
As you can see, I haven't written any code to actually use the class yet, but the "using SQLComm;" line itself is giving me this error:
Compiler Error Message: CS0246: The type or namespace name 'SqlComm' could not be found (are you missing a using directive or an assembly reference?)
As I'm still new, I'm unsure where to go from here. I seem to have included everything contained in the answer on the page I linked above. What else and I missing?
Edit: I read this post regarding a similar issue: asp.NET 2.0 Web Site Can't Access Classes in App_Code
Could this be because I am doing a website and not a web application, so the App_Code folder is being handled differently when I FTP the files over?
using SQLComm means you want to use the namespace SqlComm, which doesn't exist. I think what you want is (somewhere in your codebehind):
DataTable dt = SqlComm.SqlDataTable(...) // call one of the static methods.
You can call it directly.
Given your class has static methods only you'll call it like this:
SqlComm.SqlReturn("select * from table");
So I believe I figured it out. I had my App_Code folder within the subdirectory of my Aspx website, instead of in the root of the server. I moved the folder to the root and now it's working.
I'd be interested in hearing any answers to my edit to my original post though. Since I'm doing this as a website instead of a web application, are there any other issues I will need to keep in mind regarding using classes like this or other issues? I've looked around but haven't seen many differences.
Thanks to everyone for you help!

Categories

Resources