I have tried updateing the MS Database via c#. Although I haven't received any error, It doesn't update the database
private void Button1_Click(object sender, EventArgs e)
{
conn.Open();
string UpdateQuery = "Update NDS Set IATACode=#p2,City=#p3,Country=#p4 where ID=#p1";
OleDbCommand Update1 = new OleDbCommand(UpdateQuery, conn);
Update1.Parameters.AddWithValue("#p1", txtId.Text);
Update1.Parameters.AddWithValue("#p2", txtIata.Text);
Update1.Parameters.AddWithValue("#p3", txtCity.Text);
Update1.Parameters.AddWithValue("#p4", txtCountry.Text);
Update1.ExecuteNonQuery();
conn.Close();
ClearData();
ShowData();
MessageBox.Show("Updated");
}
OLEDB doesn't support named parameters. You need to supply parameters in order:
private void Button1_Click(object sender, EventArgs e)
{
conn.Open();
string UpdateQuery = "Update NDS Set IATACode=#p2,City=#p3,Country=#p4 where ID=#p1";
OleDbCommand Update1 = new OleDbCommand(UpdateQuery, conn);
Update1.Parameters.AddWithValue("#p2", txtIata.Text);
Update1.Parameters.AddWithValue("#p3", txtCity.Text);
Update1.Parameters.AddWithValue("#p4", txtCountry.Text);
Update1.Parameters.AddWithValue("#p1", txtId.Text);
Update1.ExecuteNonQuery();
conn.Close();
ClearData();
ShowData();
MessageBox.Show("Updated");
}
Related
I am trying to make my program able to edit the data from mysql database. this is the code for the jbutton which executes the action, after data has been entered into textfields. I want the user to enter the same 'naziv' column of the row he wants to edit, when editing.
JButton btnEdituj = new JButton("Edituj");
btnEdituj.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/csprogram","root","");
String query= "UPDATE `maticna ploca` SET `naziv`=value1,`socketi (socket1, socket2)`=value2,`chipset`=value3,`vga port`=value4,`RAM tip i MHz`=value5,`HDD`=value6,`Cijena (KM)`=value7,`Dodatno`=value8 WHERE 'naziv'=value1";
PreparedStatement pst=conn.prepareStatement(query);
pst.setString(1, textField_1.getText());
pst.setString(2, textField_2.getText());
pst.setString(3, textField_3.getText());
pst.setString(4, textField_4.getText());
pst.setString(5, textField_5.getText());
pst.setString(6, textField_6.getText());
pst.setString(7, textField_7.getText());
pst.setString(8, textField_8.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "Data updated");
pst.close();
}
catch (Exception d) {
d.printStackTrace();
}
When I use Microsoft C# windows forms application. I tried to run the login program then when I clicked the login button. it displays "Logged in as : (name of user)". then in the next form show I didn't see my name on the other form even I use some codes for the passing parameters like
Form1(codes)
public partial class Form1 : Form
{
string namesl;
OleDbCommand cm;
OleDbConnection cn;
OleDbDataReader dr;
string connection = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source =|DataDirectory|\10watts.accdb";
public Form1( )
{
cn = new OleDbConnection(connection);
cn.Open();
InitializeComponent();
}
public void getName(string _getName)
{
_getName = dr.GetValue(2).ToString();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox2.PasswordChar = '*';
cn = new OleDbConnection(connection);
cn.Open();
progressBar1.Visible = false;
}
private void btnLog_Click(object sender, EventArgs e)
{
if (textBox1.Text == String.Empty || textBox2.Text == String.Empty)
{
MessageBox.Show("Missing Requirement Field!", "Unable to Login", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
timer1.Start();
progressBar1.Visible = true;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
progressBar1.Value = progressBar1.Value + 5;
lblPercent.Text = progressBar1.Value + "%";
if (progressBar1.Value == 100)
{
timer1.Enabled = false;
string sql = #"Select * from tblUser where Username like '" + textBox1.Text + "'and Password like '" + textBox2.Text + "'";
cm = new OleDbCommand(sql, cn);
dr = cm.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
MessageBox.Show("Entered Logged In as : " + dr.GetValue(2).ToString(),"Successfully Logged in",MessageBoxButtons.OK,MessageBoxIcon.Information);
_getName = dr.getValue(2).toString();
Form2 frm2 = new Form2(this);
frm2.Show();
}
else
{
}
}
else
{
}
}
}
Form 2
public partial class Form2 : Form
{
OleDbCommand cmd;
OleDbConnection cn;
OleDbDataReader dr;
public string names;
string connection = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source =|DataDirectory|\10watts.accdb";
public Form2( )
{
cn = new OleDbConnection(connection);
cn.Open();
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
this.loggedinform.getName(names);//this thing i worried about :/
}
This whole code that I tried when I was using c# application.
Need your opinions or codes that may use for passing parameters :)
I tried some code but nothing.
Me.DataGridView1.Refresh()
Why?
My datagridview is automatically connected to database,not manualy using commands to make connection.
Try the below code... i think you except the code like below....
//Text box Change Event
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text != "")
GetData("select * from Sample where num =" + textBox1.Text);
else
GetData("select * from Sample");
}
//Data Bind Event by using BindingSource
private void GetData(string selectCommand)
{
try
{
String connectionString ="Your Connection String";
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(selectCommand, connectionString);
OleDbCommandBuilder commandBuilder = new OleDbCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
//BindingSource - Binding
sampleBindingSource.DataSource= table;
dataGridView1.AutoResizeColumns(
DataGridViewAutoSizeColumnsMode.AllCells );
}
catch (SqlException)
{
MessageBox.Show("Error Occured");
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Write(Execute("SELECT NOW()"));
}
public string Execute(string storedProcedureName)
{
using (EntityConnection connection = (EntityConnection)new EGModel.EGEntity().Connection)
{
using (EntityCommand command = connection.CreateCommand())
{
command.CommandType = CommandType.Text;
command.CommandText = storedProcedureName;
connection.Open();
return command.ExecuteScalar().ToString();
}
}
}
I am getting error "The query syntax is not valid. Near line 1, column 13."; I am very curious, why this error?
(Mysql Entity Connection)
var A = new EGModel.EGEntity().Connection;
var command = ((EntityConnection)(A)).StoreConnection.CreateCommand();
command.CommandType = System.Data.CommandType.Text;
command.CommandText = "SELECT NOW()";
((EntityConnection)(A)).StoreConnection.Open();
string id = (string)command.ExecuteScalar();
#GTSouza Thank you for your comments,
I'm trying to fill my list on Visual Studio side with help of stored procedure.
I'm using the following stored procedure:
CREATE PROCEDURE [dbo].[GetColletcion]
AS
BEGIN
select CollectionType.Name ,GlassesCollection.Name
from GlassesCollection
inner join CollectionType
on GlassesCollection.CollectionType=CollectionType.CollTypeID
END
Here's the code-behind:
protected void Button1_Click(object sender, EventArgs e)
{
List<GlassesCollection> list = new List<GlassesCollection>();
using (SqlConnection conn = new SqlConnection("Server=(local);DataBase=ISeeOptic;Integrated Security=SSPI"))
{
GlassesCollection gln = new GlassesCollection();
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetColletcion";
conn.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
gln.Name = (string)reader["CollectionType.Name"];
gln.CollectionType = (string)reader["GlassesCollection.Name"];
list.Add(gln);
}
reader.Close();
conn.Close();
}
}
But when it comes to this row:
gln.Name = (string)reader["CollectionType.Name"];
I get this Exception:
Exception Details: System.IndexOutOfRangeException: CollectionType.Name
The index outside of the range, although in database more than one record.
How can I solve my problem?
It would be best to use column aliases and refer to the columns by those instead.
CREATE PROCEDURE [dbo].[GetColletcion]
AS
BEGIN
select CollectionType.Name As TypeName ,GlassesCollection.Name As GlassesName
from GlassesCollection
inner join CollectionType
on GlassesCollection.CollectionType=CollectionType.CollTypeID
END
Then use
(string)reader["TypeName"];
(string)reader["GlassesName"];
If you cannot change your stored procedure, then you can use the oridinal position:
(string)reader[0]; //CollectionType.Name
(string)reader[1]; //GlassesCollection.Name
I corrected your typo, too. (GetCollection)
CREATE PROCEDURE [dbo].[GetCollection]
AS
BEGIN
select CollectionType.Name AS CollectionType_Name, GlassesCollection.Name AS GlassesCollection_Name
from GlassesCollection
inner join CollectionType
on GlassesCollection.CollectionType=CollectionType.CollTypeID
END
Code behind:
protected void Button1_Click(object sender, EventArgs e)
{
List<GlassesCollection> list = new List<GlassesCollection>();
using (SqlConnection conn = new SqlConnection("Server=(local);DataBase=ISeeOptic;Integrated Security=SSPI"))
{
GlassesCollection gln = new GlassesCollection();
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetCollection";
conn.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
gln.Name = (string)reader["GlassesCollection_Name"];
gln.CollectionType = (string)reader["CollectionType_Name"];
list.Add(gln);
}
reader.Close();
conn.Close();
}
}