Hi I am submitting a form to access but want to get the access assigned auto number to display in a textbox after I submit. Below it was i have, any suggestions would be great!
string cmdstr = "Insert into TaskPerformed(TaskType,OtherType,Analyst,DateCompleted)Values(#b,#c,#d,#e)";
string query2 = "Select ##IDENTITY";
OleDbConnection con1 = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con1);
OleDbCommand cmdNewID = new OleDbCommand("SELECT ##IDENTITY", con1);//
con1.Open();
cmd.CommandText = query2;
com.ExecuteNonQuery();
con1.Close();
label16.Text = cmdNewID.ToString();
It looks like the problem you're having is because you're not executing the second command... and you're closing the connection before using it
using(OleDbCommand cmdNewID = new OleDbCommand("SELECT ##IDENTITY", con1))
{
con1.Open();
cmd.CommandText = query2;
com.ExecuteNonQuery();
label16.Text = cmdNewID.ExecuteScalar();
}
Related
I am writing the following lines of code to update the data in access database.
using (OleDbConnection con = new OleDbConnection())
{
con.ConnectionString = String.Format(Queries.dbConnection, databasePath);
con.Open();
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText = "update tblusers set password = #password where userId = #userId;";
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddWithValue("#userId", authResult.UserId);
cmd.Parameters.AddWithValue("#password", newPassword);
cmd.ExecuteNonQuery();
}
}
When this line runs cmd.ExecuteNonQuery(); I got the following error:
Syntax error in UPDATE statement
Am I missing anything?
Update - 2
using (OleDbConnection con = new OleDbConnection())
{
con.ConnectionString = String.Format(Queries.dbConnection, databasePath);
con.Open();
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText = "update tblusers set password = ? where userId = ?;";
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.Add("p1", OleDbType.VarChar, 100).Value = newPassword;
cmd.Parameters.Add("p2", OleDbType.Integer).Value = authResult.UserId;
cmd.ExecuteNonQuery();
}
}
First of all: MS Access / OleDB does not used named parameters - but positional parameters. So the order in which you specify the parameters is very much relevant!
Second: OleDB uses the ? as a parameter placeholder.
So try this code:
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText = "update tblusers set [password] = ? where userId = ?;";
cmd.CommandType = System.Data.CommandType.Text;
// parameters - do *NOT* use "AddWithValue", and specify in the *correct order*!
// since the parameters are *positional*, the name provided is irrelevant
cmd.Parameters.Add("p1", OleDbType.VarChar, 50).Value = newPassword;
cmd.Parameters.Add("p2", OleDbType.Integer).Value = authResult.UserId;
cmd.ExecuteNonQuery();
}
I got error "System.Runtime.InteropServices.InvalidComObjectException: 'COM object that has been separated from its underlying RCW cannot be used.'" ONLY when i execute OleDbCommand object in using block with parameters
using (OleDbCommand comm = new OleDbCommand())
{
comm.Connection = conn;
comm.CommandType = CommandType.Text;
string txt = "SELECT* FROM [ListForGroup] WHERE [email] = #email";
comm.Parameters.Add("#email", OleDbType.VarWChar).Value = userEmail;
comm.CommandText = txt;
conn.Open();
OleDbDataReader reader = comm.ExecuteReader();
List<ListForGroups> list = returnLists(reader);
conn.Close();
cmbSelectList.DataSource = list;
cmbSelectList.DisplayMember = "listName";
cmbSelectList.ValueMember = "listForGroupsID";
}
Does anyone know reason for that. I can resolve it to use OleDbCommand object with CommandText without parameters but i read that's bad idea. And i want to do it in using block to be sure that all reasources will be released.
I resolved this problem
using (OleDbConnection conn = new OleDbConnection(connString))
{
OleDbCommand comm = new OleDbCommand();
comm.Connection = conn;
comm.CommandType = CommandType.Text;
string txt = "SELECT* FROM [ListForGroup] WHERE [email] = #email";
comm.Parameters.Add("#email", OleDbType.VarWChar).Value = userEmail;
comm.CommandText = txt;
conn.Open();
OleDbDataReader reader = comm.ExecuteReader();
List<ListForGroups> list = returnLists(reader);
cmbSelectList.DataSource = list;
cmbSelectList.DisplayMember = "listName";
cmbSelectList.ValueMember = "listForGroupsID";
}
I don't know why I didn't create OleDbConnection in brackets next to using. Another when to resolve it is to close connection after using block.
I'm trying to increment an integer in an MS Access table from a c# .net page during insert.
I'm getting a syntax error when attempting the following. Also unsure if I should be using an ExecuteNonQuery() or not?
OleDbCommand cmd = new OleDbCommand("INSERT INTO tblTarget(target,ref) VALUES(#target,(SELECT MAX(ref)+1 FROM tblTarget)", conn);
cmd.Parameters.AddWithValue("#target", TextTitle.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
You miss a bracket after tblTarget:
OleDbCommand cmd =
new OleDbCommand("INSERT INTO tblTarget(target,ref) VALUES(#target,(SELECT MAX(ref)+1 FROM tblTarget))", conn);
Here is a little review of your code, try using the using pattern:
using(var conn = new Connection())
{
conn.Open();
string sql = "INSERT INTO tblTarget(target,ref) VALUES(#target,(SELECT MAX(ref)+1 FROM tblTarget))";
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.Parameters.AddWithValue("#target", TextTitle.Text);
cmd.ExecuteNonQuery();
}
You're missing a bracket, try:
INSERT INTO tblTarget(target,ref) VALUES(#target,(SELECT MAX(ref)+1 FROM tblTarget))
But I think you are going to have other issues, you need something closer to this:
INSERT INTO tblTarget ( target, ref )
SELECT #target AS Targ, First((SELECT MAX(ref)+1 FROM tblTarget)) AS MaxRef
FROM tblTarget
GROUP BY #target;
The correct way to achieve your goal is
string sql = "INSERT INTO tblTarget (target,ref) " +
"SELECT ?, MAX(ref)+1 FROM tblTarget";
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.Parameters.AddWithValue("#target", TextTitle.Text);
cmd.ExecuteNonQuery();
I would not do the increment by the sql or code, we can use AutoNumber data type for auto increase the value in access.
string sql = "INSERT INTO tblTarget(target) VALUES(#target)";
using(var conn = new Connection())
using(OleDbCommand cmd = new OleDbCommand(sql, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#target", TextTitle.Text);
cmd.ExecuteNonQuery();
}
I'm using this video to try and populate results from a DataGridView, and am receiving the above error. The below code pertains to this error - I pass values into a stored procedure, then the final SELECT returns the values in the table in the DataGridView.
SqlConnection con = new SqlConnection();
con.ConnectionString = "integrated security=SSPI;data source=SERV;" + "persist security info=False;initial catalog=DB";
con.Open();
SqlCommand select = new SqlCommand("SELECT * FROM Table");
SqlCommand enter = new SqlCommand("sp_Proc", con);
// Stored Procedure
enter.CommandType = CommandType.StoredProcedure;
enter.Parameters.Add(new SqlParameter("#vvalue", SqlDbType.VarChar)).Value = Convert.ToString(txt1.Text);
enter.Parameters.Add(new SqlParameter("#dvalue", SqlDbType.Decimal)).Value = Convert.ToDecimal(txt2.Text);
enter.ExecuteNonQuery();
// DataGrid returns the SELECT
SqlDataAdapter sadapt = new SqlDataAdapter(select);
sadapt.SelectCommand = select;
DataTable dtab = new DataTable();
sadapt.Fill(dtab); // generates the error
BindingSource b = new BindingSource();
b.DataSource = dtab;
dGrid.DataSource = b;
sadapt.Update(dtab);
con.Close();
You did not pass connection object on the command. Try this instead,
SqlCommand select = new SqlCommand("SELECT * FROM Table", con);
You are passing connection object to your enter command but didnt pass the connection object to your select command
SqlCommand select = new SqlCommand("SELECT * FROM Table");
SqlCommand enter = new SqlCommand("sp_Proc", con);
Use this
SqlCommand select = new SqlCommand("SELECT * FROM Table",con);
SqlCommand cmd = new SqlCommand("sp_StockAnalysis2") // connection missing in sqlcommand
SqlCommand cmd = new SqlCommand("sp_StockAnalysis2",Connection())// pass connection
I'm trying to make a simple test program that can open MDB files and do 3 basic things
the MDB have 3 fields, all of them are text:
ID
INFO
TEXT
showing data acording to ID = got this working
changing data according to ID = problem
adding new data = problem
the show data works with this code:
con = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = c:\\mdb\\testmdb.mdb");
cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "select Info, text from Table1 where ID = '" + int.Parse(textBox1.Text) + "' ";
con.Open(); // open the connection
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox2.Text = dr["Info"].ToString();
textBox3.Text = dr["text"].ToString();
}
con.Close();
How do I insert new data in MDB and update data I already have?
Working code
using System;
using ADOX;
using System.Data.OleDb;
using System.Data;
using System.IO;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
CreateMdb("toster_ru.mdb");
string fileNameWithPath = Environment.CurrentDirectory + "\\toster_ru.mdb";
CreateTableInToMdb(fileNameWithPath);
InsertToMdb(fileNameWithPath);
UpdateToMdb(fileNameWithPath);
var myDataTable = new DataTable();
using (var conection = new OleDbConnection("Provider = Microsoft.JET.OLEDB.4.0; Data Source = " + fileNameWithPath))
{
conection.Open();
var query = "Select info From my_table";
var adapter = new OleDbDataAdapter(query, conection);
adapter.Fill(myDataTable);
Console.WriteLine(myDataTable.Rows[0][0].ToString()); //output: toster2.ru
Console.ReadKey();
}
}
static void CreateMdb(string fileNameWithPath)
{
if (File.Exists(fileNameWithPath))
return;
Catalog cat = new Catalog();
string connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Jet OLEDB:Engine Type=5";
cat.Create(String.Format(connstr, fileNameWithPath));
cat = null;
}
static void InsertToMdb(string fileNameWithPath)
{
var con = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = " + fileNameWithPath);
var cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "insert into my_table (ID, [Info], [text]) values (#ID, #Info, #text);";
cmd.Parameters.AddWithValue("#ID", 1);
cmd.Parameters.AddWithValue("#Info", "toster.ru");
cmd.Parameters.AddWithValue("#text", "blabla");
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
static void UpdateToMdb(string fileNameWithPath)
{
var con = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = " + fileNameWithPath);
var cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "UPDATE my_table SET [Info] = ?, [text] = ? WHERE ID = ?;";
cmd.Parameters.AddWithValue("#p1", OleDbType.VarChar).Value = "toster2.ru";
cmd.Parameters.AddWithValue("#p2", OleDbType.VarChar).Value = "blabla2";
cmd.Parameters.AddWithValue("#p3", OleDbType.VarNumeric).Value = 1;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
static void CreateTableInToMdb(string fileNameWithPath)
{
try
{
OleDbConnection myConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + fileNameWithPath);
myConnection.Open();
OleDbCommand myCommand = new OleDbCommand();
myCommand.Connection = myConnection;
myCommand.CommandText = "CREATE TABLE my_table([ID] NUMBER, [Info] TEXT, [text] TEXT)";
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
}
catch { }
}
}
}
Try this for insert:
con = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = c:\\mdb\\testmdb.mdb");
cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "insert (ID, Info, text) into Table1 values (#ID, #Info, #text);";
cmd.Parameters.AddWithValue("#ID", textBox1.Text);
cmd.Parameters.AddWithValue("#Info", textBox2.Text);
cmd.Parameters.AddWithValue("#text", textBox3.Text);
con.Open(); // open the connection
//OleDbDataReader dr = cmd.ExecuteNonQuery();
cmd.ExecuteNonQuery();
con.Close();
Try this for update:
con = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = c:\\mdb\\testmdb.mdb");
cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "update Table1 set [Info] = #Info, [text] = #text where ID = #ID;";
cmd.Parameters.AddWithValue("#ID", textBox1.Text);
cmd.Parameters.AddWithValue("#Info", textBox2.Text);
cmd.Parameters.AddWithValue("#text", textBox3.Text);
con.Open(); // open the connection
//OleDbDataReader dr = cmd.ExecuteNonQuery();
cmd.ExecuteNonQuery();
con.Close();
For more operations, examine the left panel of this site.