I have a query
SELECT * FROM db_tabel WHERE someStringField=\'#someStringValue\'
and i know that #someStringValue exists in tabel
but MySqlDataReader object told me than query returns nothing
where is mistake?
C# code:
const string command = "SELECT * FROM `db_tabel` WHERE `varcharvalue`=\'#varcharvalue\'";
var connection = new MySqlConnection(_connectionString);
try
{
connection.Open();
}
catch (Exception ex)
{
Log.Error(ex.ToString());
return null;
}
var cmd = new MySqlCommand(command, connection);
cmd.Parameters.AddWithValue("#varcharvalue",val );
MySqlDataReader reader;
try
{
reader = cmd.ExecuteReader();
}
catch (Exception ex)
{
connection.Close();
Log.Error(ex.ToString());
return null;
}
reader.Read();
if (reader.HasRows)
{
var cl = GetInstanse(reader);
reader.Close();
connection.Close();
return cl;
}
reader.Close();
connection.Close();
return null;
Related
listbox is emptyI want to take data from my sql and insert it into my listbox form but i can't. By compiling listbox is empty. What do i wrong?
private: System::Void listBox1_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e)
{
String^ SQLconnection = "Server = localehost; Uid = root; Password = pass123; Database = details";
MySqlConnection^ conn = gcnew MySqlConnection(SQLconnection);
MySqlCommand^ cmd = gcnew MySqlCommand("SELECT * FROM details.material;", conn);
MySqlDataReader^ reader;
try
{
conn->Open();
reader = cmd->ExecuteReader();
while (reader->Read())
{
listBox1->Text +=(reader->GetInt32(0));
}
}catch (Exception^ ex)
{
MessageBox::Show(ex->Message);
}
}
I'm new to ASP.NET and I'm stuck on this problem. I get the error:
Error:System.InvalidOperationException: The connection was not closed. The connection's current state is open. at System.Data.ProviderBase.DbConnectionInternal.
Here is my code, the error points towards 'while' statement. I've tried number of things but nothing worked. I know that I need to close connection when if-statement is true but don't know how. Can anyone help me on this? Thanks.
protected void loadtour()
{
try
{
conn.Open();
string strSelect = "Select * From Agents where Agent_ID='" + AgID.Text + "'";
SqlCommand cmd = new SqlCommand(strSelect, conn);
SqlDataReader myReader = cmd.ExecuteReader();
while (myReader.Read())
{
if (myReader["Agent_Status"].ToString() == "On Tour")
{
Label1.Text = "Assigned Tour Details:";
try
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT PackageInfo.pkg_Name, PackageInfo.pkg_Type, PackageInfo.pkg_Status, Packages.pkg_Country, Packages.pkg_Start, Packages.pkg_End, PackageInfo.Agent_ID, PackageInfo.Agent_Name FROM PackageInfo INNER JOIN Packages ON PackageInfo.pkg_ID = Packages.pkg_ID WHERE(PackageInfo.Agent_ID = '" + AgID.Text + "')", conn);
DataTable ds = new DataTable();
da.Fill(ds);
gv1.DataSource = ds;
gv1.DataBind();
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
conn.Close();
}
else
{
Label1.Text = "No Tour Assigned Yet!";
}
myReader.Close();
conn.Close();
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
//Do stuff with the connection
}
Wrap your connection in a using block. This guarantees it always gets closed.
I have a database named as "test" in which I have a table named as "first" which contains raw data, I want to get this table data. What should be the prepare statement I have to use in order to get data from table "first" ? Below is the code I am trying. Any help or guidance would be appreciable.
#Path("/database") // Specific URL
#GE
#Produces(MediaType.TEXT_PLAIN)
public String returnDB_Status() throws Exception {
PreparedStatement query = null;
String result = null;
Connection conn = null;
try {
conn = mysql_prac.dbConn().getConnection(); // this works fine ...
query = conn.prepareStatement("SELECT * from first" ); // Table named as "first" is placed inside the connected database.
ResultSet rs = query.executeQuery();
result = "Data received : " + rs;
query.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null)
conn.close();
}
return result;
}
and the source code used get a connection
public class mysql_prac {
private static DataSource mysql_prac = null;
private static Context context = null;
public static DataSource dbConn() throws Exception {
if (mysql_prac != null) {
return mysql_prac;
}
try {
if (context == null) {
context = new InitialContext();
}
mysql_prac = (DataSource) context.lookup("JDBC_ref"); //JNDI ID (JDBC_REF)
} catch (Exception e) {
e.printStackTrace();
}
return mysql_prac;
}
}
You must loop through the ResultSet to get the fields of each row. So I made the following edit together with some comments.Please notice the comments.
try {
conn = mysql_prac.dbConn().getConnection(); // this works fine ...
query = conn.prepareStatement("SELECT * from first" ); // Table named as "first" is placed inside the connected database.
ResultSet rs = query.executeQuery();//You must loop through the results set to get the fields of each row
while(rs.next()){
String dbUserID = rs.getString("column1");//this is just an example to retrieve all data in the column called 'column1'
result = "Data received : " + dbUserID;
System.out.println(result);
}
query.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null)
conn.close();
}
I am trying to connect to a MySQL database from a jsp page using jdbc in the backend.
I have the following code:
public static void insertIntoDatabase(String code,String name,String temp,String hum,String del) {
Connection con = null;
if (del.length() == 0) {
del="no data";
}
name = name.replaceAll("\\(.+?\\)", "");
name = name.replaceAll(" ", "_");
del = del.replaceAll(" ", "_");
System.out.println("del "+del);
String url = "jdbc:mysql://localhost:3306/test";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url,"root","");
con.createStatement().executeUpdate("CREATE TABLE IF NOT EXISTS aiportdetails(code VARCHAR(50) PRIMARY KEY, " +
"name VARCHAR(250), temp VARCHAR(50), hum VARCHAR(50), del VARCHAR(50))");
ResultSet rs = con.prepareStatement("SELECT * FROM airportdetails;").executeQuery();
} catch (SQLException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (con != null) {
con.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
I am getting the following error at
ResultSet rs = con.prepareStatement("SELECT * FROM airportdetails;").executeQuery();
error:
Table 'test.airportdetails' doesn't exist
But from my phpmyadmin I can see that the table is created and exists:
What is the reason I am getting this error?
Thank you.
executeUpdate()
Executes the SQL statement in this PreparedStatement object, which must be an SQL INSERT, UPDATE or DELETE statement; or an SQL statement that returns nothing, such as a DDL statement.
Currently you are trying to use this for creating a table. That's the reason why you are getting that error.
Refer to the documentation Java 6 OR Java 1.4.2 for executeUpdate
EDIT:
You should create a table using Statement
Statement st = con.createStatement();
String table = "Create table .......";
st.executeUpdate(table);
you can put the initialize the connection and load driver at the constructor level, then in the method you can first createt check the table if it exists or create it then if it is successful, continue with the insert operation.like this:
public class MyBean{
String url = "jdbc:mysql://localhost:3306/test,"root","" ";
public MyBean(){
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url);
}catch(Exception e){
}
}
public static void insertIntoDatabase(String code,String name,String temp,String hum,String del) {
Connection con = null;
if (del.length() == 0) {
del="no data";
}
name = name.replaceAll("\\(.+?\\)", "");
name = name.replaceAll(" ", "_");
del = del.replaceAll(" ", "_");
System.out.println("del "+del);
try {
con = DriverManager.getConnection(url);
Int result = con.createStatement().executeUpdate("CREATE TABLE IF NOT EXISTS aiportdetails(code VARCHAR(50) PRIMARY KEY, " +
"name VARCHAR(250), temp VARCHAR(50), hum VARCHAR(50), del VARCHAR(50))");
if(result>0){
try{
ResultSet rs = con.prepareStatement("SELECT * FROM airportdetails;").executeQuery();
}catch(Exception e){
}finally{
}
}//end if
} catch (SQLException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (con != null) {
con.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
I have a MYSQL database with 50.000 rows. Each row represents an article. I want the value of the column with they name "articletext" to be split into 50.000 files. One file for each row. I'm new to MYSQL so I'm not sure how to do this.
Can anyone help me?
Thanks
I created this small java application to solve the problem.
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Opening connection");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost/articles", "username", "password");
String query = "Select title,articletext from articles";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String title = rs.getString(1);
String text = rs.getString(2);
try {
FileWriter fstream = new FileWriter(title + ".txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(text);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("Closing connection");
con.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And I propose my solution using Python:
import MySQLdb
def write_to_file(with_name, write_this):
with_name = str(with_name)
with open(with_name, "w") as F:
F.write(write_this)
db = MySQLdb.connect(
host="localhost", # hostname, usually localhost
user="andi", # your username
passwd="passsword", # your password
db="db_name", # name of the database
charset = "utf8", # encoding
use_unicode = True
)
cur = db.cursor()
cur.execute("select id, description from SOME_TABLE")
for row in cur.fetchall() :
write_to_file(row[0], row[1].encode('utf8'))
where row[0] will map to id, row[1] will map to description