There is no problem in code but the output is nothing - c#

how are you,sir my code is correct means there is no error after debugging that code.My goal is that if the user click on button(which is placed in default.aspx,for example)then the database table is created in database(database placed within sql express),I write the code for that purpose we debug the code and there is no error in the code .when i click the button(in runtime).when i check the database(which is in the sql express)there is no table is created in that database.please sir solve my problem.The code written in c# behind the button is that:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
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 PractiseWeb.DataSet1TableAdapters;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Diagnostics;
using System.ComponentModel;
using System.Text;
using System.Data.SqlClient;
using System.Data.Odbc;
using ADOX;
using ADODB;
public partial class _Default : System.Web.UI.Page
{
SqlConnection conn;
SqlCommand cmd;
string connectionString = ConfigurationManager.ConnectionStrings["gameConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
conn = new SqlConnection(connectionString);
if (!(conn.State == ConnectionState.Open))
{
conn.Open();
}
string sql = "CREATE TABLE mySchoolRecord(StudentId INTEGER CONSTRAINT PkeyMyId PRIMARY KEY, Name CHAR(50)," + "Address CHAR(255)," + "Contact INTEGER));";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
sql = "INSERT INTO mySchoolRecord (StudentId, Name,Address,Contact) VALUES (1, 'Mr. Manish', " + " 'Sector-12,Noida', 2447658 );";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
sql = "INSERT INTO mySchoolRecord (StudentId, Name,Address,Contact) VALUES (2, 'Mr. Ravi', " + " 'New Delhi', 2584076521 );";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
sql = "INSERT INTO mySchoolRecord (StudentId, Name,Address,Contact) VALUES (3, 'Mr. Peter', " + " 'United States', 25684124 );";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
THANKS SIR

Remove the try-catch and see what's happening. Writing to the console isn't going to help much in an ASP.NET app. :)
using System;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection conn;
SqlCommand cmd;
string connectionString = ConfigurationManager.ConnectionStrings["gameConnectionString"].ConnectionString;
protected void Button1_Click(object sender, EventArgs e)
{
using (conn = new SqlConnection(connectionString))
{
if (!(conn.State == ConnectionState.Open))
{
conn.Open();
}
string sql = "CREATE TABLE mySchoolRecord(StudentId INTEGER CONSTRAINT PkeyMyId PRIMARY KEY, Name CHAR(50)," + "Address CHAR(255)," + "Contact INTEGER));";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
sql = "INSERT INTO mySchoolRecord (StudentId, Name,Address,Contact) VALUES (1, 'Mr. Manish', " + " 'Sector-12,Noida', 2447658 );";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
sql = "INSERT INTO mySchoolRecord (StudentId, Name,Address,Contact) VALUES (2, 'Mr. Ravi', " + " 'New Delhi', 2584076521 );";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
sql = "INSERT INTO mySchoolRecord (StudentId, Name,Address,Contact) VALUES (3, 'Mr. Peter', " + " 'United States', 25684124 );";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
}
}

#sayyer ,
follow the below steps
1)can you copy your sql and paste on sqlserver directly and see if it creating or not?? do a break on exception while debuggin ,it will tell you if there are any exceptions in the code
2) Check your database connection
3) check all the formating for the insert statements.
Best way to fix the issue is do ctr + alt + E and check break on exceptions, that will fix your problem

Try removing semicolons from SQL queries.

Related

How to click on a label in a listBox and have text show up in multiple textBoxs

I am designing a planner and I'm having in issue when I click on my add task button. Once I click on it, my program crashes and this error is displayed:
"System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword 'table'.'"
Where would I find the incorrect syntax?
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.SqlClient;
namespace InfoHub
{
public partial class Planner : Form
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\epoch\source\repos\InfoHub\InfoHub\planner.mdf;Integrated Security=True;Connect Timeout=30");
public Planner()
{
InitializeComponent();
}
private void Planner_Load(object sender, EventArgs e)
{
this.TopMost = true;
}
private void addTask_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into table values('" + textBox3.Text+"','"+textBox4.Text+"','"+textBox5.Text+"','"+textBox6.Text+"','"+textBox7.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
textBox3.Text = "";
textBox4.Text = "";
textBox5.Text = "";
textBox6.Text = "";
textBox7.Text = "";
}
You are using sql insert command incorrectly:
cmd.CommandText = "insert into table values('" + textBox3.Text+"','"+textBox4.Text+"','"+textBox5.Text+"','"+textBox6.Text+"','"+textBox7.Text+"')";
table is sql keyword and it is not treated as table name. Try adding writing it as 'table' to inform sql that 'table' is name of particular table and not keyword:
cmd.CommandText = "insert into 'table' values('" + textBox3.Text+"','"+textBox4.Text+"','"+textBox5.Text+"','"+textBox6.Text+"','"+textBox7.Text+"')";
generally it is good practice to always write names in ' '.

C# Insert Into syntax error

I am trying to insert data into a table in MS Access. I keep getting the error Missing semicolon (;) at end of SQL statement. or a different error saying that i my Insert query needs to have a value or table in it. 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 System.Data.OleDb;
using System.Data.SqlClient;
namespace MiddleWare
{
public partial class Sales : Form
{
public Sales()
{
InitializeComponent();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
int empId = int.Parse(txtEmpID.Text);
string cmdText = #"INSERT INTO [Sales]
([Printers], [Ink], [Paper])
VALUES (#Printers,#Ink,#Paper)
SELECT #EmpID FROM (Emplopyee)";
using (OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\cp-stud-nas1\users\mat72462\Documents\SalesData.accdb"))
using (OleDbCommand cmd = new OleDbCommand(cmdText, con))
{
con.Open();
cmd.Parameters.AddWithValue("#Printers", OleDbType.VarWChar).Value = txtPrinters.Text;
cmd.Parameters.AddWithValue("#Ink", OleDbType.VarWChar).Value = txtInk.Text;
cmd.Parameters.AddWithValue("#Paper", OleDbType.VarWChar).Value = txtPaper.Text;
cmd.Parameters.AddWithValue("#EmpID", OleDbType.VarWChar).Value = txtEmpID.Text;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#EmpID", txtEmpID.Text);
cmd.CommandText = "SELECT [Total Sales] FROM Sales WHERE EmpID=#EmpID";
string result = cmd.ExecuteScalar().ToString();
MessageBox.Show(result);
}
}
private void Sales_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'DataSet1.DataTable1' table. You can move, or remove it, as needed.
this.DataTable1TableAdapter.Fill(this.DataSet1.DataTable1);
}
private void btnReport_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\cp-stud-nas1\users\mat72462\Documents\SalesData.accdb");
{
this.DataTable1TableAdapter.Fill(this.DataSet1.DataTable1);
this.reportViewer1.RefreshReport();
}
}
}
}
You should seperate the queries by semicolon
string cmdText = #"INSERT INTO [Sales]
([Printers], [Ink], [Paper])
VALUES (#Printers,#Ink,#Paper);
SELECT #EmpID FROM (Emplopyee)";
Also you can't pass the column name as parameter. In that case use dynamic query.
you should change the query to this:
string cmdText = #"INSERT INTO [Sales]
([Printers], [Ink], [Paper], [EmpID])
VALUES (#Printers,#Ink,#Paper,
SELECT EmpID FROM (Employee) )";
It most likely should read:
string cmdText = #"INSERT INTO [Sales]
([Printers], [Ink], [Paper], [EmpID])
VALUES (#Printers, #Ink, #Paper, #EmpID)";
The "cmd.Paramter.AddWithValue" are unnecessary.
Try formatting your cmdText as
cmd = "INSERT INTO [Sales] ([Printers], [Ink], [Paper])
VALUES (" + txtPrinters.Text + " ," + txtInk.Text + ", " + txtPaper.Text + ")
This clears up confusion of "cmd.Paramter.AddWithValue" duplicating or overriding values.
Rewritten btnUpdate_Click (also not sure if Emplopyee is a typo or not)
private void btnUpdate_Click(object sender, EventArgs e)
{
using (OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\cp-stud-nas1\users\mat72462\Documents\SalesData.accdb"))
using (OleDbCommand cmd = new OleDbCommand(cmdText, con))
{
con.Open();
cmd = "INSERT INTO [Sales] ([Printers], [Ink], [Paper]) VALUES (" + txtPrinters.Text + " ," + txtInk.Text + ", " + txtPaper.Text + ") SELECT " + textEmpID.Text + " FROM (Emplopyee)";
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT [Total Sales] FROM Sales WHERE EmpID=#EmpID";
string result = cmd.ExecuteScalar().ToString();
MessageBox.Show(result);
}
}

SqlCommand connection string for localhost database

I am trying to create a simple website in VS Express for Web 2013 which can interact with a database "Parts." My database is stored in the app_data folder. I am able to view the connection in the Server Explorer, which implies the connection string is saved. However, the following code throws 2 errors:
Error 13 The best overloaded method match for 'System.Data.SqlClient.SqlCommand.SqlCommand(string, System.Data.SqlClient.SqlConnection)' has some invalid arguments
Error 14 Argument 2: cannot convert from 'string' to 'System.Data.SqlClient.SqlConnection'
I don't know how to remedy this. Here is my c# code:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void insertButton_Click(object sender, EventArgs e)
{
string connstring = System.Configuration.ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
SqlCommand cmd = new SqlCommand("INSERT INTO PARTS VALUES('" + nameBox.Text + "', '" + descriptionBox.Text + "', '" + quantityBox.Text + "', '" + categoryList.SelectedValue + "')", connstring);
cmd.ExecuteNonQuery();
}
}
I'm completely new to c#, so please keep that in mind. Thanks for your help.
UPDATE: The following code throws two errors, both of which are:
Error 15 The name 'conn' does not exist in the current context
I'm new to c#, but it doesn't look like there's anything wrong with the code. The name "conn" is clearly defined right above.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void insertButton_Click(object sender, EventArgs e)
{
using (var conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connect"].ConnectionString))
using (var cmd = new SqlCommand(
"INSERT INTO PARTS VALUES(#name, #description, #quantity, #category)", conn))
{
cmd.Parameters.AddWithValue("name", nameBox.Text);
cmd.Parameters.AddWithValue("description", descriptionBox.Text);
cmd.Parameters.AddWithValue("quantity", quantityBox.Text);
cmd.Parameters.AddWithValue("category", categoryList.SelectedValue);
conn.Open();
cmd.ExecuteNonQuery();
}
}
}
using(var conn = new SqlConnection(connectionString))
{
conn.Open();
// use conn to create the command
}
But important: YOUR SQL IS REALLY REALLY DANGEROUS. That is open to SQL injection, a HUGE and trivially easy attack surface. Please please parameterize that.
For example:
using(var conn = new SqlConnection(connectionString))
using(var cmd = new SqlCommand(
"INSERT INTO PARTS VALUES(#name, #description, ...)", conn))
{
cmd.Parameters.AddWithValue("name", nameBox.Text);
cmd.Parameters.AddWithValue("description", descriptionBox.Text);
//...
conn.Open();
cmd.ExecuteNonQuery();
}
(note you need to add a few yourself; I have left it incomplete, just name and description used for example)
What is connect value from your config?
Can you try
SqlConnection conn = new SqlConnection(connstring);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
and now issue the query.
You need to create a SqlConnection first:
string connstring = System.Configuration.ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
SqlConnection conn = new SqlConnection(connstring);
SqlCommand cmd = new SqlCommand("INSERT INTO PARTS VALUES('" + nameBox.Text + "', '" + descriptionBox.Text + "', '" + quantityBox.Text + "', '" + categoryList.SelectedValue + "')"
, conn);
cmd.ExecuteNonQuery();
Some early habits to get into:
Do not concatenate SQL strings. This is for several reasons, not the least of which is the vulnerability to SQL Injection attacks.
wrap your connection and command in using statements. That ensures that the connections are closed properly if there is an exception.
The end result will look something like:
string connstring = ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
using(SqlConnection conn = new SqlConnection(connstring))
{
string sql = "INSERT INTO PARTS VALUES(#name, #description, #quantity, #categoryList)"
using(SqlCommand cmd = new SqlCommand(sql , conn))
{
cmd.Parameters.AddWithValue("#name", nameBox.Text);
... etc.
cmd.ExecuteNonQuery();
}
}

Info repeatedly getting recorded in DB

I have a Form where I am inserting a record into the database. There are two tables, table_1 is called members, and table_2 is called Amount.
I am using two SQL INSERT statements to send records to database , because that’s the way I have figured out -- there might be other ways, which I don’t know.
When I insert the record I get a message that it is inserted successfully, but when I check the database the inserted record replaces the one present , so I have last record in the DB repeated several times. Please assist.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CemiyetAidatSistem
{
public partial class AddMember : Form
{
public AddMember()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection("Data Source=My-PC\\SQLSERVER;Initial Catalog=FredericiaDernek;Integrated Security=True");
private void btnInsert_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
string Sql = "INSERT INTO Uyeleri ( dID, FullName, Address, Mobile, Email, Comments ) VALUES ('" + txtdID.Text + "', '" + txtAdiSoyadi.Text + "','" + txtAddress.Text + "','" + txtMobile.Text + "','" + txtEmail.Text + "','" + txtComments.Text + "')";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "INSERT INTO Aidat (dID Year, Amount ) VALUES ('"+ txtdID.Text +"','" + txtYear.Text + "','" + txtAmount.Text + "')";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
MessageBox.Show("Data Added Scuessfully");
}
}
}
I have rewritten your code to correct errors and bad practices
string connString = "Data Source=My-PC\\SQLSERVER;Initial Catalog=FredericiaDernek;Integrated Security=True";
private void btnInsert_Click(object sender, EventArgs e)
{
using(SqlConnection con = new SqlConnection(connString))
{
con.Open();
string Sql = "INSERT INTO Uyeleri (dID, FullName, Address, Mobile, Email, Comments ) " +
"VALUES (#id, #name, #address, #mobile, #email, #comments");
using(SqlCommand cmd = new SqlCommand(Sql, con))
{
cmd.Parameters.AddWithValue("#id", txtdID.Text);
cmd.Parameters.AddWithValue("#name", txtAdiSoyadi.Text);
cmd.Parameters.AddWithValue("#address", txtAddress.Text);
cmd.Parameters.AddWithValue("#mobile", txtMobile.Text);
cmd.Parameters.AddWithValue("#email", txtEmail.Text);
cmd.Parameters.AddWithValue("#comments", txtComments.Text);
cmd.ExecuteNonQuery();
Sql = "INSERT INTO Aidat (dID, [Year], Amount ) VALUES " +
"(#id, #year, #amount)";
cmd.Parameters.Clear();
cmd.CommandText = Sql; // <- missing this in the previous version.....
cmd.Parameters.AddWithValue("#id", txtdID.Text);
cmd.Parameters.AddWithValue("#name", txtYear.Text);
cmd.Parameters.AddWithValue("#amount", txtAmount.Text);
cmd.ExecuteNonQuery();
}
}
What I have changed:
The second insert statement is wrong. Missing a comma between first
and second column
Removed the creation of the SqlConnection at the global level
Added appropriate using statement to dispose the SqlConnection and
SqlCommand also in case of exceptions
Used parameters for the two insert statements
Added square brackets around Year field (Year is a reserved keyword
in T-SQL)
Creating a SqlConnection at the global level is bad, because you grab system resources and you don't dispose them for the lifetime of your application. And the situation could be out of control in case of exceptions not correctly handled.
Now I have some doubt about your tables. The fields dID (both tables) and Amount are of text type (varchar,nvarchar)?. If they are of numeric type it is necessary to add a conversion before adding the values to the Parameters collection
I would also suggest changing your for loop to clear the controls replace this
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
with the following code using linq.
this.Controls.OfType<TextBox>().ToList().ForEach(textBox => textBox.Clear());
keep in mind that 'this' will refer to the name of your Form
so it would be
(YourWinFormsName).Controls.OfType<TextBox>().ToList().ForEach(textBox => textBox.Clear());

if the user click on button then the database table is created in database through asp.net with c#,how can do?

My question is that if the user click on button (which is place in default.aspx, for example) then the database table is created in database (SQL express), how can do that?
I have tried but errors are occuring during debugging, errors are:
the best overloaded method match for 'system.data.odbc.odbc command.odbc command(string,system.data.odbc.odbc connection)'has some invalid arguments.
Argument'2':cannot convert from 'system.data.sqlclient.sqlconnection' to 'system.data.odbc.odbc connection'.
The code written in c# behind the button (button is placed in default.aspx, for example) is:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
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 PractiseWeb.DataSet1TableAdapters;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Diagnostics;
using System.ComponentModel;
using System.Text;
using System.Data.SqlClient;
using System.Data.Odbc;
using ADOX;
using ADODB;
public partial class _Default : System.Web.UI.Page
{
SqlConnection conn;
OdbcCommand cmd;
string connectionString = ConfigurationManager.ConnectionStrings["gameConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
conn = new SqlConnection(connectionString);
if (!(conn.State == ConnectionState.Open))
{
conn.Open();
}
string sql = "CREATE TABLE mySchoolRecord(StudentId INTEGER CONSTRAINT PkeyMyId PRIMARY KEY,"
+ "Name CHAR(50)," + "Address CHAR(255)," + "Contact INTEGER));";
cmd = new OdbcCommand(sql,conn);// in this line above two errors occurred
cmd.ExecuteNonQuery();
sql = "INSERT INTO mySchoolRecord (StudentId, Name,Address,Contact) VALUES (1, 'Mr. Manish', " + " 'Sector-12,Noida', 2447658 );";
cmd = new OdbcCommand(sql,conn);// in this line above two errors occurred
cmd.ExecuteNonQuery();
sql = "INSERT INTO mySchoolRecord (StudentId, Name,Address,Contact) VALUES (2, 'Mr. Ravi', " + " 'New Delhi', 2584076521 );";
cmd = new OdbcCommand(sql,conn);// in this line above two errors occurred
cmd.ExecuteNonQuery();
sql = "INSERT INTO mySchoolRecord (StudentId, Name,Address,Contact) VALUES (3, 'Mr. Peter', " + " 'United States', 25684124 );";
cmd = new OdbcCommand(sql,conn);// in this line above two errors occurred
cmd.ExecuteNonQuery();
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
catch (OdbcException ex)
{
Console.WriteLine(ex);
}
}
}
You're mixing ADO (SQLConnection) and ODBC (ODBCCommand). Use SQLCommand instead if you're using SQL Server, or ODBCCommand if you're not. You can't mix the two.
Try this
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
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 PractiseWeb.DataSet1TableAdapters;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Diagnostics;
using System.ComponentModel;
using System.Text;
using System.Data.SqlClient;
using System.Data.Odbc;
using ADOX;
using ADODB;
public partial class _Default : System.Web.UI.Page
{
SqlConnection conn;
OdbcCommand cmd;
string connectionString = ConfigurationManager.ConnectionStrings["gameConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
conn = new SqlConnection(connectionString);
if (!(conn.State == ConnectionState.Open))
{
conn.Open();
}
string sql = "CREATE TABLE mySchoolRecord(StudentId INTEGER CONSTRAINT PkeyMyId PRIMARY KEY,"
+ "Name CHAR(50)," + "Address CHAR(255)," + "Contact INTEGER));";
cmd = new SqlCommand(sql,conn);// in this line above two errors occurred
cmd.ExecuteNonQuery();
sql = "INSERT INTO mySchoolRecord (StudentId, Name,Address,Contact) VALUES (1, 'Mr. Manish', " + " 'Sector-12,Noida', 2447658 );";
cmd = new SqlCommand(sql,conn);// in this line above two errors occurred
cmd.ExecuteNonQuery();
sql = "INSERT INTO mySchoolRecord (StudentId, Name,Address,Contact) VALUES (2, 'Mr. Ravi', " + " 'New Delhi', 2584076521 );";
cmd = new SqlCommand(sql,conn);// in this line above two errors occurred
cmd.ExecuteNonQuery();
sql = "INSERT INTO mySchoolRecord (StudentId, Name,Address,Contact) VALUES (3, 'Mr. Peter', " + " 'United States', 25684124 );";
cmd = new SqlCommand(sql,conn);// in this line above two errors occurred
cmd.ExecuteNonQuery();
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
catch (OdbcException ex)
{
Console.WriteLine(ex);
}
}
}
Replacing OdbcCommand by SqlCommand will solve your problem
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Data.SqlClient;
public object connection()
{
SqlConnection myConnectionString = new SqlConnection("Data Source=(local)\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True;Pooling=False");
double[] a = new double[6];
string myCommand = null;
myCommand = "CREATE database soft_billing";
SqlCommand cmd = new SqlCommand(myCommand, myConnectionString);
try {
for (int k = 0; k <= 4; k++) {
a(k) = 0.0;
}
cmd.Connection.Open();
cmd.ExecuteNonQuery();
t.Enabled = true;
t.Interval = 10;
ProgressBar1.Value = 0;
cmd.Connection.Close();
} catch {
Interaction.MsgBox(" Already installed database", MsgBoxStyle.Critical, " MaS InfoTech- Warning");
}
try {
SqlConnection cn = new SqlConnection("Data Source=(local)\\SQLEXPRESS;Initial Catalog=soft_billing;Integrated Security=True;Pooling=False");
string sql = null;
sql = "CREATE TABLE customer(cus_name varchar(50) NULL,address varchar(50) NULL,mobno numeric(18, 0) NULL,tin varchar(50) NULL,kg varchar(50) NULL)";
cmd = new SqlCommand(sql, cn);
// , connection);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
} catch {
Interaction.MsgBox(" Already installed database", MsgBoxStyle.Critical, " MaS InfoTech- Warning");
}
}

Categories