I'm using sqlite compact edition,I done some tests using linqdpad, worked fine. But when I go to C# code, it not works. I tried get fields from database with following code:
using System;
using System.Data.SqlServerCe;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var conStr = #"data source=C:\path\db.sdf;password=...";
var con = new SqlCeConnection(conStr);
con.Open();
var cmd = new SqlCeCommand("select * from quest", con);
SqlCeDataReader result = cmd.ExecuteReader();
Console.Write(result.Read());
Console.ReadLine();
con.Close();
}
}
}
result.Read() returns false. as if had not fields. how I fix it?
Using linqpad I can see something like:
query:
select * from quest;
UPDATE
The problem happens when the database(.sdf) uses a password.
check the semicolon in the end of your query.maybe by delete it your query execute right.
in other hand every thing is correct generally.
It looks alright to me - maybe this:
var result
Change it to SqlCeDataReader. Its the only 'mistake' I can see.
Also don't forget to close the connection after you're done.
Related
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.
Hi all Oracle experts,
I have a rather strange behaviour of a very very simple program only intended to test basic data acquisition from a remote Oracle database with C#.
I have created a simple C# program as follows:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Oracle.ManagedDataAccess.Client;
class Program
{
static void Main(string[] args)
{
var connectionString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP) (HOST={{Server}})(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME={{DataSource}})));User Id={{Username}};Password={{Password}};";
connectionString = connectionString.Replace("{{DataSource}}", "Actual service name");
connectionString = connectionString.Replace("{{Server}}", "Actual Server IP");
connectionString = connectionString.Replace("{{Username}}", "Actual username");
connectionString = connectionString.Replace("{{Password}}", "Actual password");
using (connection = new OracleConnection {ConnectionString = connectionString})
{
connection.Open();
using ( var cmd = connection.CreateCommand() )
{
cmd.CommandText = "SELECT * FROM Table";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
i++;
}
}
}
}
}
}
The table I am reading from has 220.000 entries, and the problem with the code is, that after an amount of "rows" the reader.Read() just stops. It is supposed to return "false" if there are no more records, and there are still records to come, but the Read() function is called and never returns. Even after letting it try for hours it does not come back.
Does anyone have had a similar experience?
I already heard not to use the Microsoft Oracle Data Driver, so I am using the one from oracle. But still the problem does not go away.
The amount of rows retrieved changes if you change the SQL Command, but also not in a very understandable way: I thought if this has to do with the network buffers I can reduce the columns to get more rows, but it works in the opposite direction. More columns result in more rows.
Any help is deeply appreciated.
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!
I'm a real noob in .NET and i'm trying to link a simple command line application (in C#) with a SQL server database. I'm now able to connect the program with the database but not to recover the data that are in it. Here is my code :
using System;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
string connectionString = GetConnectionString();
string queryString = "SELECT USER_ID FROM dbo.ISALLOCATEDTO;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = queryString;
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
int i = 0;
while (reader.Read())
{
i++;
Console.WriteLine("Field "+i);
Console.WriteLine("\t{0}",reader[0]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
//Console.WriteLine("Hello world");
string x = Console.ReadLine();
}
static private string GetConnectionString()
{
return "Data Source=FR401388\\SQLEXPRESS;Initial Catalog=Test;";
+ "Integrated Security=SSPI";
}
}
}
But when i'm running it and even if my table is not empty (I've seen it in the sql server studio), I cannot recover the data by using the read() method.
What I've done so far : try to change the name of the datatable with a fake one : the datatable is not found (so the link between sql server database and programm seems to be valid).
I'm using Windows Authentication in sql server, dunno if it's changing anything... (Once again : i'm very new to all of that).
Thanks !
Your code should work.
A possible cause is: You are looking at a different database.
This is quite common if you use Server Explorer inside VS with a connectionstring different from the one used in code.
I am trying to write t-sql in C# (visual studio). I have this code to connect to the database:
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 System.Data.SqlClient;
using Microsoft.SqlServer.Server;
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn;
connetionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Xtreme\\Desktop\\CardsDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}
Where/how do I write the T-SQL code and how do I get the result?
Can someone give me an simple select example in my code?
You can use DataAdapter.Fill Method:
try
{
using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM Employee", cnn))
{
// Use DataAdapter to fill DataTable
DataTable t = new DataTable();
a.Fill(t);
// Render data onto the screen
dataGridView1.DataSource = t; //if you want.
}
}
catch (Exception ex)
{
MessageBox.Show("Problem!");
}
Create a SqlCommand and set the CommandType to CommandType.Text. Then add your SQL to the CommandText property of the SqlCommand.
SqlCommand command = new SqlCommand(commandName, (SqlConnection)Connection);
command.CommandType = CommandType.Text;
command.CommandText = "SELECT * FROM MyTable";
IDataReader result = command.ExecuteReader();
Ardman already showed you how to execute any arbitary sql command. But what i didn't answer very well, is where to put your sql statement.
I think it is a very bad behaviour and also not very good to read if you put your statement directly into the code.
A better method (in my eyes) is the following:
Within your project create a new folder (maybe called Queries)
Right click this folder and select Add - New Item
In the dialog just select Textfile and give it the name about what this query will do
Make sure you replace the file extension from .txt to .sql
Just put your statement right into this file
In the Resource Editor add this file as a resource
Now you can access this sql statement within your project just by using Properties.Resources.MySqlStatement