Simple C# connection to .accdb file - c#

All I want to do is to retrieve data from tables in .accdb file.
Here is my full application:
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 System.Data.OleDb;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection myConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Microland.accdb;Persist Security Info=False;");
myConn.Open();
OleDbCommand myQuery = new OleDbCommand("select CustID from Customers WHERE CustID = 1;", myConn);
OleDbDataReader myReader = myQuery.ExecuteReader();
if(myReader.HasRows)
{
myReader.Read();
label1.Text = myReader.ToString();
}
myConn.Close();
}
}
}
I think I am missing some using at the very top or my code is somewhat broken becasue then I click the button1 the label1 text changes to System.Data.OleDb.OleDbDataReader.
Also is this the correct way to connect to access data base (.accdb) Do I need to do this walkthrough in order for it to work or this is irrelevant to what I need to do?
Thanks for any information! Very appreciated

When you call myReader.ToString() it returns a string that represents the current object. So "System.Data.OleDb.OleDbDataReader" is exactly that.
It seems like you want the label to be equal to the data that's read. I'm not familiar with this reader in particular, but refer here for documentation.
You'll need to call one of the Get*() functions.

label1.Text = myReader["CustID"] as string; // if nullable field
Or
label1.Text = (string)myReader["CustID"] // if not null

Related

No mapping exists from object type c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string SaveLayout(string layout, object state)
{
SqlConnection conn = new SqlConnection(#"Persist Security Info=False;User ID=admin;Password=admin123;Initial Catalog=Test_Layout;Data Source=Myserver");
conn.Open();
SqlCommand cmd = new SqlCommand("insertlayout", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#layout", layout);
cmd.Parameters.AddWithValue("#states", state);
cmd.ExecuteNonQuery();
conn.Close();
return "successfully state saved";
}
}
i am using webmethod(using Json,jquery) to store object in sql server 2008
but i am getting following error on sql server 2008 i am using varchar(max) datatype for storing object(state variable) in database how to convert state variable(object) to string to store in database
The problem is that you have to pass a string instead of dictionary. I may suggest you to serialise your dictionary and pass that value to AddWithValue function. Let JSON be the format of serialisation. I would recommend Json.net as serialization library. It provides convenient way of dictionary serialization/deserialization.
So your code may look like this:
cmd.Parameters.AddWithValue("#states", JsonConvert.SerializeObject(state));
P.S. better use using statement both for SqlConnection and SqlCommand objects.
If you want to store any object use VARBINARY(MAX) in sqlserver like
sqlCmd.Parameters.Add("#states", SqlDbType.VarBinary, Int32.MaxValue);
sqlCmd.Parameters["#states"].Value = state;
here state will be your object

How do I use C# queries on a prexisting database(SQLite database)?

I have run into a problem where my C# code is creating a whole new database instead of using a preexisting one. Then my program runs into errors where the program cannot find the table to insert the information even though the preexisting database has the table because the code itself is looking at the new table. Here is 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.Threading.Tasks;
using System.Windows.Forms;
using Finisar.SQLite;
namespace WestSlope
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SQLiteConnection sqlite_conn;
SQLiteCommand sqlite_cmd;
//SQLiteDataAdapter sqlite_datareader;
sqlite_conn = new SQLiteConnection("DataSource=ClientLogDB.db;Version=3;New=True;Compress=True;");
//open conection
sqlite_conn.Open();
//create sql commands
sqlite_cmd = sqlite_conn.CreateCommand();
//Let SQLite command know query is known
sqlite_cmd.CommandText = "INSERT INTO ASAM (ASAMone, ASAMtwo, ASAMthree, ASAMfour, ASAMLim, ASAMLimEX) VALUES ('Had to call', 'Reffered', 'Had to call', 'Watched', 1 , 'Injured legs');"
;
//execute query
sqlite_cmd.ExecuteNonQuery();
sqlite_conn.Close();
}
}
}
What the code is supposed to do is when the user presses a button the program will save information to the preexisting database; but, as you can see the program is making a new database instead of using the preexisting one.
Use new=false in your connection string to use existing database file.
Following should be the connection string:
sqlite_conn = new SQLiteConnection("DataSource=ClientLogDB.db;Version=3;New=False;Compress=True;");

Why am I getting a CS1502 (invalid arguments) error from this code?

I'm facing this issue and I don't know the reason behind it. Here's the error Visual Studio is reporting:
The best overloaded method match for 'PostForum.INSERTforum(int, string, string, System.DateTime)' has some invalid arguments
I'm using Oracle to store my data and also created a procedure called INSERTFORUM. I am not sure if I have a problem with the stored procedure or something else. Please help me sort out this issue.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Forum : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string course_Id = DropDownList1.Text;
int ccourse_Id = Convert.ToInt32(course_Id);
string question = TextBox1.Text;
string posterName = TextBox2.Text;
DateTime blog_date = DateTime.Now;
PostForum.INSERTforum(course_Id, question, posterName, blog_date);
}
}
Code for :Postforum.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public class PostForum
{
public static int INSERTforum(int course_Id, string question, string posterName, DateTime blog_date)
{
int rowsAffected = 0;
using (SqlConnection connection = ConnectionManager.GetDatabaseConnection())
{
SqlCommand command = new SqlCommand("INSERTforum", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#course_Id", SqlDbType.Int).Value = course_Id;
command.Parameters.Add("#question", SqlDbType.VarChar).Value = question;
command.Parameters.Add("#posterName", SqlDbType.VarChar).Value = posterName;
command.Parameters.Add("#blog_date", SqlDbType.DateTime).Value = blog_date;
rowsAffected = command.ExecuteNonQuery();
}
return rowsAffected;
}
}
INSERTforum expects an int as the first parameter. You're passing it a string. Correct your invocation of INSERTforum to read:
PostForum.INSERTforum(ccourse_Id, question, posterName, blog_date);
Note that this will fail if DropDownList1.Text can't be parsed as an integer.
Don't forget to look at the Error List tab in Visual Studio. The error you saw was only the first - the next error would have given you the information I did.

removing form from c# code?

I'm extremely new to C# and programming anything except for SQL. I've gotten the below code to happen on a Form and on a button click. If I wanted to just make this run on open, how would I do that? I'm very new to C# as you can tell (just started today learning it but its pretty exciting!)
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 Oracle.DataAccess.Client; // ODP.NET Oracle managed provider
using Oracle.DataAccess.Types;
namespace OraTrigger
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string oradb = "Data Source=OMP1;User Id=user;Password=pass;";
OracleConnection conn = new OracleConnection(oradb); // C#
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT cast(Count(*) as varchar(20)) as trig FROM ZDMSN.TRIGGER_TEST";
//cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
int cnt;
if (int.TryParse(dr.GetString(0), out cnt))
{
if (cnt > 0)
{
System.Diagnostics.Process.Start(#"C:\testfile.bat");
}
}
cmd.CommandText = "TRUNCATE TABLE ZDMSN.TRIGGER_TEST";
conn.Dispose();
}
}
}
If you need to run your code as a scheduled task then a command line application is more suitable.
Just create a new project and select Console Application.
Then move all of your button click code inside the Main method written for you by the Visual Studio IDE.
Rembember to set the references to the Oracle ODP.NET library and import the relevant using statements
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Oracle.DataAccess.Client; // ODP.NET Oracle managed provider
using Oracle.DataAccess.Types;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string oradb = "Data Source=OMP1;User Id=user;Password=pass;";
using(OracleConnection conn = new OracleConnection(oradb))
using(OracleCommand cmd = new OracleCommand("SELECT Count(*) as trig FROM ZDMSN.TRIGGER_TEST", conn))
{
conn.Open();
int cnt = (int)cmd.ExecuteScalar();
if (cnt > 0)
{
System.Diagnostics.Process.Start(#"C:\testfile.bat");
cmd.CommandText = "TRUNCATE TABLE ZDMSN.TRIGGER_TEST";
cmd.ExecuteNonQuery();
}
}
}
}
}
I have also revised your code to get a single value from the database. For this case is enough to use the Command.ExecuteScalar method that returns the first column of the first row obtained from your sql command text. Because the count(*) should Always return a single row you could easily cast the return value of ExecuteScalar to your record count variable.
EDIT I have added the logic to TRUNCATE the table involved. Please pay attention that you should use the code provided here. Your code will probably fail because you have an open DataReader and when a DataReader is open you cannot execute other commands (This is true for SqlServer without Multiple Active Result Sets enabled, I really don't know if this rules applies also to the Oracle NET Provider)
Subscribe to Shown or Load event of form and move your code to that event handler.
Form.Shown Event Occurs whenever the form is first displayed.
Form.Load Event Occurs before a form is displayed for the first time.
Also I suggest to extract your code to some Data Access related class, or at least to separate method. And call that method from event handler.

Connection failed with MySQL .NET Connector

I cannot connect to MySQL it fails on line connection.Open(), is there something wrong with my code ?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace MySQLConnection
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string MyConString = "SERVER=localhost:3316;" +
"DATABASE=mydb;" +
"UID=user;" +
"PASSWORD=password;";
MySqlConnection connection = new MySqlConnection(MyConString);
connection.Open();
// ...
connection.Close();
}
}
}
this is the string format I use to connect via the MySql.Data.dll version 6.1.2.0
server={0};user id={1};password={2};database={3};port={4}
so your connection string should be
server=localhost;user id=user;password=password;database=mydb;port=3316
You need to specify the Port as a separate argument in the connection string and it looks like the password key is "Pwd" instead of "Password".
See connectionstrings.com for help on the exact syntax.

Categories

Resources