Access import into SQL server not importing first line - sql-server-2008

I am using a function to import data from a access db into SQL server:
public string importDataFromAccess(string table, string fileName)
{
OleDbConnection OleDbConn = new OleDbConnection(String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}", fileName));
try
{
string sSQLTable = table;
string myExcelDataQuery = "Select * from " + sSQLTable;
string sSqlConnectionString = connStr;
string sClearSQL = "DELETE FROM " + sSQLTable;
SqlConnection SqlConn = new SqlConnection(sSqlConnectionString);
SqlCommand SqlCmd = new SqlCommand(sClearSQL, SqlConn);
SqlConn.Open();
SqlCmd.ExecuteNonQuery();
SqlConn.Close();
OleDbCommand OleDbCmd = new OleDbCommand(myExcelDataQuery, OleDbConn);
OleDbConn.Open();
OleDbDataReader dr = OleDbCmd.ExecuteReader();
SqlBulkCopy bulkCopy = new SqlBulkCopy(sSqlConnectionString);
bulkCopy.DestinationTableName = sSQLTable;
while (dr.Read())
{
bulkCopy.WriteToServer(dr);
}
OleDbConn.Close();
return "Done";
}
catch (Exception ex)
{
OleDbConn.Close();
return ex.ToString();
}
}
I noticed it isnt importing the first record of each table, can anyone help notice why and how to fix? Hopefully it is only the first row...

You shouldn't need the
while (dr.Read())
{
bulkCopy.WriteToServer(dr);
}
And you just need to replace that with
bulkCopy.WriteToServer(dr);
The WriteToServer method
Copies all rows in the supplied IDataReader to a destination table
specified by the DestinationTableName property of the SqlBulkCopy
object.
But the dr.Read() that you have called has read the first line out of the Reader and advanced the IDataReader to the next record (so it is not accessible to the WriteServer method).

Related

Numeric value insert as 0 in accessdatabase

I am creating one application where data are inserted into access table using DataGridView. The issue is that two value(s) are inserted correctly but when I'm trying to insert numeric value it's inserted as 0.
private void dataGridView1_RowLeave(object sender, DataGridViewCellEventArgs e)
{
try
{
if (dataGridView1.IsCurrentRowDirty)
{
string connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string cmd1 = "insert into Medicine_Available_Detail([Medicine_Name],[Dealer_name],[total_available])values(?,?,?)";
OleDbCommand cmd = new OleDbCommand(cmd1, con);
cmd.CommandType = CommandType.Text;
string Medicine_Name = dataGridView1.Rows[e.RowIndex].Cells["Medicine_Name"].Value.ToString();
cmd.Parameters.AddWithValue("#Medicine_Name", Medicine_Name);
string Dealer_name = dataGridView1.Rows[e.RowIndex].Cells["Dealer_name"].Value.ToString();
cmd.Parameters.AddWithValue("#Dealer_name", Dealer_name);
int Availability;
bool total_availableHasValue = int.TryParse(dataGridView1.Rows[e.RowIndex].Cells["total_available"].Value.ToString(), out Availability);
cmd.Parameters.AddWithValue("#total_available", Availability);
con.Open();
int n = cmd.ExecuteNonQuery();
con.Close();
if (n > 0)
{
MessageBox.Show("Data Inserted Successfully", "Data Inserted ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
Presumably "Availability" is the numeric value. Are you sure that the value from the datagridview for total_available is numeric? If it's not, then Available will be = 0.
You could try testing total_availableHasValue after the parse or log/debug to check on the contents of the datagridview cell.

How to store a Dictionary in a MySQL database?

Can some one demonstrate how I can save the values of a dictionary into a MySQL database?
public void Update()
{
Dictionary<string,int> t = new Dictionary<string,int>();
for(int i = 0; i < t.Count;i++)
{
//What comes Here?
}
}
First fix your iteration loop, second it is up to you to decide, eg:
MySqlConnection conDataBase = new MySqlConnection(constring);
conDataBase.Open();
foreach (KeyValuePair<string, string> entry in)
{
string constring = "..........";
string Query = "insert into Tablename values(#par1,#par2)";
MySqlCommand cmd = new MySqlCommand(Query, conDataBase);
cmd.Parameters.AddWithValue( "#par1",entry.Key)
cmd.Parameters.AddWithValue("#par2",entry.Value)
//Execute command
cmd.ExecuteNonQuery();
}

Displaying Database records to JTable in JAVA swing

I am trying to display the database records in the Jtable but i m not getting the code right. I m using IDE netbeans and database is mysql. I can see the panel and the scroll pane but the table is not displayed. I think something is wrong in the table properties or dont know if its invisible.
My code is as follows:
try{
panel_paylist.setVisible(true);
String dbUrl = "jdbc:mysql://localhost/hostel";
String dbClass = "com.mysql.jdbc.Driver";
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection(dbUrl,"root","17121990");
System.out.println("Connected!!!!");
MainScreen obj = new MainScreen(conn);
String[] columnNames = {"First Name",
"Last Name",
"Amount Recvd.",
"Date","Cheque/cash","cheque no","Balance Amt.","Total Amt.",
"Vegetarian"};
ResultSet rs = null;
Statement sql= null;
ArrayList<Object[]> data = new ArrayList<>();
String query="SELECT firstname,lastname, amountreceivd,dte,creditcashcheque,cheque_no,balance_amt, totalamount,Remark FROM payment;";
sql = con.createStatement();
sql.executeQuery(query);
rs = sql.getResultSet();
while(rs.next()){
Object[] row = new Object[]{rs.getString(1),
rs.getString(2),
rs.getInt(3),
rs.getString(4),
rs.getString(5),
rs.getString(6),
rs.getInt(7),
rs.getInt(8),
rs.getString(9)};
data.add(row);
}
Object[][] realData = data.toArray(new Object[data.size()][]);
table_paylist= new JTable(realData, columnNames);
scroll_paylist= new JScrollPane(table_paylist);
table_paylist.setPreferredScrollableViewportSize(new Dimension(800, 200));
table_paylist.setFillsViewportHeight(true);
panel_paylist.setLayout(new BorderLayout());
panel_paylist.add(scroll_paylist, BorderLayout.CENTER);
}
catch(Exception e)
{
}
please help
first of all you are missing port number of localhost.
change
"jdbc:mysql://localhost/hostel"
to
"jdbc:mysql://localhost:3306/hostel";
second point dont use semicolon(;) at the end of sql string. i. e. remove semicolon from
"SELECT firstname,lastname, amountreceivd,dte,creditcashcheque,cheque_no,balance_amt, totalamount,Remark FROM payment;"
and you can also try this one
public DefaultTableModel PlayList() throws ClassNotFoundException,SQLException,ParseException
{
String[] columnNames = {"First Name","Last Name","Amount Recvd.","Date","Cheque/cash","cheque no","Balance Amt.","Total Amt.","Vegetarian"};
DefaultTableModel dtm = new DefaultTableModel(columnNames , 0);
dtm.setColumnCount(9);
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:8080/hostel","root","17121990");
PreparedStatement ps1 = null;
ResultSet rs1 = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
ps1=conn.prepareStatement("SELECT firstname,lastname,mountreceivd,dte,creditcashcheque,cheque_no,balance_amt,totalamount,Remark FROM payment");
rs1 = ps1.executeQuery();
while(rs1.next())
{
dtm.addRow(new Object[]{rs1.getString(1)
rs.getString(2),
rs.getInt(3),
rs.getString(4),
rs.getString(5),
rs.getString(6),
rs.getInt(7),
rs.getInt(8),
rs.getString(9)});
}
}
finally
{
rs1.close();
ps1.close();
conn.close();
}
return dtm;
}
now use PlayList() method as a argument of your jtable's setmodel method;
i. e. jtable.setmodel(PlayList());
Use rs2xml third party Jar file to display query results.This is very helpful

Iam not able to retrieve completely the data from sql?

public string getString()
{
con.ConnectionString = ConnString;
con.Open();
string sp = "select top 3 hotelid from hotel order by NEWID()";
SqlCommand cmd = new SqlCommand(sp, con);
SqlDataAdapter sa = new SqlDataAdapter(cmd);
cmd.ExecuteNonQuery();
reader = cmd.ExecuteReader();
while (reader.Read()) //Call Read to move to next record returned by SQL //OR call --While(reader.Read())
{
det = reader[0].ToString();
}
reader.Close();
con.Close();
return det;
}
When I'm executing this code I'm able to retrieve only a single item of data?,
but when I am executing the SQL query I am able to retrieve randomly 3 items of data.
You are overwriting the det variable on each while loop.
You either need to create a collection and add to it, or concatenate the string (note the +=)...
det += reader[0].ToString();
UPDATE
As suggested above, another option is to create a collection, something like...
public List<string> getString()
{
...
List<string> ret = new List<string>;
while (reader.Read())
ret.Add(reader[0].ToString());
...
return ret;
}

MySQL System.FormatException: Input string was not in a correct format

Currently, I am creating an application using ASP.NET MVC3 and MySQL and when I try to retrieve a user's first name from the databse I receive a System.FormatException: Input string was not in a correct format.
This is my code:
public string GetUserFirstName(UInt64 id)
{
DBConnections databaseCnnString = new DBConnections();
string connectionString = "server=123.123.com;user=me;database=db1;port=3306;password=abcdef";
MySqlConnection cnn = new MySqlConnection(connectionString);
try
{
cnn.Open();
string sp_GetFName = "SP_GET_FNAME";
MySqlCommand cmd = new MySqlCommand(sp_GetFName, cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("id", id);
cmd.Parameters["id"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("first_name", MySqlDbType.VarChar);
cmd.Parameters["first_name"].Direction = ParameterDirection.Output;
object result = cmd.ExecuteScalar();
if (result != null)
{
string fname = Convert.ToString(result);
return fname;
}
else
{
string fname = "friend";
return fname;
}
}
catch (Exception ex)
{
throw (ex);
}
finally
{
cnn.Close();
cnn.Dispose();
}
}
This is MySQL Stored Procedure:
CREATE DEFINER=`0001`#`%` PROCEDURE `SP_GET_FNAME`(IN id BIGINT(20), OUT first_name VARCHAR(60))
BEGIN
DECLARE user_id BIGINT(20) DEFAULT id;
DECLARE output VARCHAR(60);
SELECT `FName` FROM `users` WHERE USERID=user_id INTO output;
SET first_name = output;
END
The problem seems to be when executing cmd.ExecuteScalar().
What is my problem here?
Thank you in advance!
Copy and paste error on my part. The correct code that works as expected is:
public string GetUserFirstName(UInt64 id)
{
DBConnections databaseCnnString = new DBConnections();
string connectionString = "server=123.123.com;user=me;database=db1;port=3306;password=abcdef";
MySqlConnection cnn = new MySqlConnection(connectionString);
try
{
cnn.Open();
string sp_GetFName = "SP_GET_FNAME";
MySqlCommand cmd = new MySqlCommand(sp_GetFName, cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("id", id);
cmd.Parameters["id"].Direction = ParameterDirection.Input;
cmd.Parameters.Add(new MySqlParameter("first_name", MySqlDbType.VarChar));
cmd.Parameters["first_name"].Direction = ParameterDirection.Output;
cmd.ExecuteScalar();
string fname = Convert.ToString((cmd.Parameters["first_name"].Value));
return fname;
}
catch (Exception ex)
{
throw (ex);
}
finally
{
cnn.Close();
cnn.Dispose();
}
}
CORRECTION: cmd.Parameters.Add(new MySqlParameter("first_name", MySqlDbType.VarChar));
NOT: cmd.Parameters.AddWithValue("first_name", MySqlDbType.VarChar);
In my case, the FNAME field in the user table cannot be NULL; therefore, checking for NULL values returned in the code is not necessary.
I would guess that the user is not found or the fname is null.
And I really hope you're not querying the database for each user column.
Good luck.
An additional comment.
When trying to return a string value the AddWithValue appears to be trying to convert the output from a string into a number. This results in the string format exception.