public void query2(View V)
{
Log.i("Android"," MySQL Connect Example.");
Connection conn = null;
try {
String driver = "net.sourceforge.jtds.jdbc.Driver";
Class.forName(driver).newInstance();
String connString = "jdbc:jtds:sqlserver://10.0.2.2:1433/demo;integratedSecurity=true;user=usd;password=dell#123;";
conn = DriverManager.getConnection(connString);
Log.w("Connection","open");
// Statement stmt = conn.createStatement();
PreparedStatement ps;
ps=conn.prepareStatement("insert into UserMaster1 values(?,?)");
//int x=stmt.executeUpdate("insert into UserMaster1 values( 'usaid','mansoori')");
ps.setString(1,un);
ps.setString(2,pwd);
Log.d("exupdt","insertion done");
Toast.makeText(this, "Success", Toast.LENGTH_LONG).show();
ps.executeUpdate();
Log.d("PreparedStmt","Success");
conn.close();
}
catch (Exception e)
{
Log.w("Error connection","" + e.getMessage()); }
}
}
i am inserting data in sql server by using the interface PreparedStatement by android to sql server but only a blank row inserted not the data how can i insert dynamic values
You cannot directly access your remote database.
You have to write web-service on server side and then send request from your android application to this service.
You can use this tutorial for example of implementing such program.
public class MainActivity extends Activity {
private TextView t1,t2,t3;
private Button b1;
private EditText e1,e2;
String un,pwd;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1=(TextView)findViewById(R.id.tv1);
t2=(TextView)findViewById(R.id.tv2);
t3=(TextView)findViewById(R.id.tv3);
b1=(Button)findViewById(R.id.btn);
e1=(EditText)findViewById(R.id.ed1);
e2=(EditText)findViewById(R.id.ed2);
if (android.os.Build.VERSION.SDK_INT> 9){
StrictMode.ThreadPolicy policy =new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
}
public void query2(View V)
{
un =e1.getText().toString();
pwd =e2.getText().toString();
if(un.equals("")||pwd.equals(""))
Toast.makeText(this,"Above Fields cannot be left blank",Toast.LENGTH_LONG).show();
else
{
Connection conn = null;
try {
String driver = "net.sourceforge.jtds.jdbc.Driver";
Class.forName(driver).newInstance();
String connString = "jdbc:jtds:sqlserver://172.22.0.2:1433/Samay;integratedSecurity=true;user=DBSQL;password=samay#123;";
conn = DriverManager.getConnection(connString);
Log.w("Connection","open");
PreparedStatement ps;
ps=conn.prepareStatement("insert into UserMaster1 values(?,?)");
ps.setString(1,un);
ps.setString(2,pwd);
int x;
x=ps.executeUpdate();
Log.d("exupdt",un);
Log.d("exupdt",pwd);
Toast.makeText(this, "Success"+x, Toast.LENGTH_LONG).show();
Log.d("PreparedStmt","Success");
conn.close();
}
catch (Exception e)
{
Log.w("Error connection","" + e.getMessage()); }
}
}
}
My best friend solve this typical problem very logically i don't understand why you people don't give the exact answer instead of successions
my best friend name is s.(java queen) she simply solve this problem by giving
un =e1.getText().toString();
pwd =e2.getText().toString();
this code after the method query2 and program gives the exact result what i wanted ..i got dynamic insertion android to sql server...
Related
My android application is supposed to get data from an Azure SQL database, but the queries keep responding with
Reference to database and/or server name is not supported in this
version of SQL Server
On the server side audit log it just states
Reference to database and/or server name in 'delivery.dbo.upload' is
not supported in this version of SQL Server
Code:
public class CheckDeliveries extends AsyncTask<String, String, String> {
String z = "";
Boolean isSuccess = false;
private ArrayList<ModelU> arrayList;
//#Override
protected void onPostExecute(String r) {
if (z == "ok") {
GetDeliveries adapter = new GetDeliveries(ViewUpcoming.this, arrayList);
mRecyclerView.setAdapter(adapter);
}
Context context = getApplicationContext();
CharSequence text = "2 " + z;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
#Override
protected String doInBackground(String... strings)
{
try
{
con = connectionclass();
if (con == null)
{
z = "Internet Issue";
}
else
{
String query = "SELECT * FROM [delivery].[dbo].[upload]";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
z = "ok";
if(rs.next()) {
do {
#SuppressLint("Range") ModelU modelu = new ModelU(
"" + rs.getInt(rs.getInt("ID")),
"" + rs.getString(rs.getInt("Name")),
"" + rs.getString(rs.getInt("Address")),
"" + rs.getString(rs.getInt("Status"))
);
arrayList.add(modelu);
}
while (rs.next());
}
else {
z = "Invalid Query";
isSuccess = false;
}
}
} catch (Exception ex) {
isSuccess = false;
z = ex.getMessage();
}
return z;
}
}
#SuppressLint("NewApi")
public Connection connectionclass() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection = null;
String ConnectionURL = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnectionURL = "jdbc:jtds:sqlserver://2033051.database.windows.net:1433;database=delivery;user=XXXXXXXX;password=XXXXXXXX;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;ssl=request;loginTimeout=30;";
connection = DriverManager.getConnection(ConnectionURL);
}
catch (SQLException se)
{
Log.e("error 1", se.getMessage());
}
catch (ClassNotFoundException e)
{
Log.e("error 2", e.getMessage());
}
catch (Exception e)
{
Log.e("error 3", e.getMessage());
}
return connection;
}
}
Toastbox output
Azure database
Any help is greatly appreciated!
This error occurs because Azure does not allow to alter the master database. To resolve this, you need to connect directly to the Azure database you are going to use.
Delete the SQL Azure linked server that we created and create a new one.
Under the Server type section of the General tab, choose the Other data source radio button. The name for the linked server in the Linked server text box can be, this time, whatever you like (e.g. AZURE SQL DATABASE). Under the Provider drop down box, choose the Microsoft OLE DB Provider SQL Server item. In the Data source text box, enter the name of the SQL Azure (e.g. server.database.windows.net). The most important setting in order to correctly create a linked server to an Azure SQL database is to enter the name in the Catalog text box (e.g. TestDatabase) of an Azure SQL database for which you want to create a linked server to an Azure SQL database. Otherwise, if this field is left empty, we will encounter the same 40515 error when trying to get a list of the tables under the Catalogs folder.
Refer this article by Marko Zivkovic
I'm trying to use MySQL while learning Android, but this class not found exception occurs. I have imported the MySQL connecter jar file into my project, and I have set it up. I googled about the problem but only got a tomcat solution of the same problem but I still don't know how to solve this in Android.
private class GetData extends AsyncTask<String,String,String> {
String msg = "";
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://"+
DBStrings.DATABASE_URL +"/"+
DBStrings.DATABASE_NAME;
#Override
protected void onPreExecute(){
progressTextView.setText("Connecting to database");
}
#Override
protected String doInBackground(String... strings) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL,DBStrings.USERNAME,DBStrings.PASSWORD);
stmt = conn.createStatement();
String sql = "SELECT * FROM medicine";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
Integer ID = rs.getInt("ID");
String name = rs.getString("Name");
Integer date = rs.getInt("Date");
medID.add(ID);
names.add(name);
medDate.add(date);
}
msg = "complete!";
rs.close();
stmt.close();
conn.close();
}catch (SQLException connERROR)
{
msg = "An exception was thrown for JDBC";
connERROR.printStackTrace();
}catch (ClassNotFoundException classERROR)
{
msg = "Class not found exception";
classERROR.printStackTrace();
}finally {
}
return null;
}
}
Don't use JDBC from an android device, just use J2EE servlets (simplest solution if you want to code in JAVA), and call these servlet from android through HTTP (you can use Retrofit Library to make these calls https://square.github.io/retrofit).
I'm working on android login app with online SQL server database that I have to access it from any platform. I opened the 1433 port and and connect with my ip address and did all the configuration in SQL server still cannot connect from my phone while I can connect from the android studio easily.
Please help me, perhaps I'm missing little things.
MainActivity.java
public class MainActivity extends AppCompatActivity {
ConnectionClass connectionClass;
EditText edtuserid,edtpass;
Button btnlogin;
ProgressBar pbbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectionClass = new ConnectionClass();
edtuserid = (EditText) findViewById(R.id.edtuserid);
edtpass = (EditText) findViewById(R.id.edtpass);
btnlogin = (Button) findViewById(R.id.btnlogin);
pbbar = (ProgressBar) findViewById(R.id.pbbar);
pbbar.setVisibility(View.GONE);
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DoLogin doLogin = new DoLogin();
doLogin.execute("");
}
});
}
public class DoLogin extends AsyncTask<String,String,String>
{
String z = "";
Boolean isSuccess = false;
String userid = edtuserid.getText().toString();
String password = edtpass.getText().toString();
#Override
protected void onPreExecute() {
pbbar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String r) {
pbbar.setVisibility(View.GONE);
Toast.makeText(MainActivity.this,r,Toast.LENGTH_SHORT).show();
if(isSuccess) {
Intent i = new Intent(MainActivity.this, attendance.class);
startActivity(i);
finish();
}
}
#Override
protected String doInBackground(String... params) {
if(userid.trim().equals("")|| password.trim().equals(""))
z = "Please enter User Id and Password";
else
{
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with The server";
} else {
String query = "select * from tablename where id='" + userid + "' and Password='" + password + "'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs.next())
{
z = "Login successfull ";
isSuccess=true;
}
else
{
z = "Invalid Credentials";
isSuccess = false;
}
}
}
catch (Exception ex)
{
isSuccess = false;
z = "Exceptions";
}
}
return z;
}
}
}
ConnectionClass.java
public class ConnectionClass {
String ip = "192.168.....etc";
String classs = "net.sourceforge.jtds.jdbc.Driver";
String db = "dbname";
String un = "sql server login username";
String password = "*****";
#SuppressLint("NewApi")
public Connection CONN() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String ConnURL = null;
try {
Class.forName(classs);
ConnURL = "jdbc:jtds:sqlserver://" + ip + ";"
+ "databaseName=" + db + ";user=" + un + ";password="
+ password + ";";
conn = DriverManager.getConnection(ConnURL);
} catch (SQLException se) {
Log.e("ERRO", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERRO", e.getMessage());
} catch (Exception e) {
Log.e("ERRO", e.getMessage());
}
return conn;
}
}
Manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
The DB can be local, but you must configure your network so it can be reach from the outside.
First
If you want to have the DB at your local server, you must ensure to have a fixed IP from you ISP or use other means to ensure that you IP is always reachable even when the IP change (no-ip and such can do this for you).
Second
You must do the Port forward from the router to you DB Server, so when it gets a connection it will redirect to you DB Server.
My advice is to have it in a hosting service
lately i've been trying to develop a app in Android Studio that it should print results in my emulador, but since i'm a beginner in this field(Java/Android) i searched a lot and i discover that the difference between my code and the others code has been that i'm trying to connect directly from my Android App to SQL, and what i really want it's to connect from Android to Network(of my company) and then connect to SQL Server, can someone help me?
Here it is the code i develop: (Android App directly to SQL Server)
public class manutencao extends Activity {
Button executar;
EditText buscar;
ListView listar;
Connection connect;
SimpleAdapter dataAdapt;
private void declarar()
{
executar = (Button) findViewById(R.id.btn_Executar);
buscar = (EditText) findViewById(R.id.et_campo);
listar = (ListView) findViewById(R.id.listView);
}
private void inicializar()
{
declarar();
buscar.setText("SELECT TOP 10 * FROM Gav_Auto_Manutencao_Autonoma");
connect = CONN("*user","*pass", "GAV_Manutencao", "*ip");
}
#SuppressLint("NewApi")
private Connection CONN(String _user, String _passe, String _BD, String _server)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String connURL = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
connURL = "jdbc:jtds:sqlserver://" + _server + ";" + "databaseName=" + _BD + ";user=" + _user + ";password=" + _passe + ";";
conn = DriverManager.getConnection(connURL);
} catch (SQLException se) {
Log.e("Erro", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("Erro", e.getMessage());
} catch (Exception e) {
Log.e("Erro", e.getMessage());
}
return conn;
}
public void QuerySQL(String comandoSQL){
ResultSet rs;
try {
Statement statement = connect.createStatement();
rs = statement.executeQuery(comandoSQL);
List<Map<String, String>> data = null;
data = new ArrayList<Map<String, String>>();
while(rs.next()){
Map<String, String> datanum = new HashMap<String, String>();
datanum.put("A", rs.getString("Posto"));
data.add(datanum);
}
String[] from = {"A"};
int [] views = {R.id.txt_titulo, R.id.txt_conteudo};
dataAdapt = new SimpleAdapter(this, data, R.layout.modelo, from, views);
listar.setAdapter(dataAdapt);
} catch (Exception e) {
Log.e("ERRO", e.getMessage());
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manutencao);
inicializar();
executar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
QuerySQL(buscar.getText().toString());
}
});
}
An android app that can send direct sql queries to the companies database?
I think you should go the HTTP/JSON way.
http://developer.android.com/training/volley/index.html
Hello I try to get data from my oracle database, I use ojdbc14.jar. There is no error in the code but I got this error in the run time 05-17 10:41:06.846: E/dalvikvm(456): Could not find class 'oracle.security.pki.OracleWallet', referenced from method oracle.jdbc.driver.OracleDriver.getSecretStoreCredentials
How to fix this error. This is my code to get data from database
try
{
String username = getDataFromOraDB();
TextView tv = new TextView(this);
tv.setText(username);
}
catch(SQLException e)
{
Toast.makeText(getApplicationContext(), e.getMessage(), 1).show();
}
catch(ClassNotFoundException e)
{
Toast.makeText(getApplicationContext(), e.getMessage(), 1).show();
}
}
public String getDataFromOraDB() throws SQLException, ClassNotFoundException
{
String name = null;
String jdbcURL = "jdbc:oracle:thin:#localhost:1521:xe";
String user = "SYSTEM";
String password = "radit";
try
{
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
Connection conn;
ResultSet rs;
Statement stmt;
conn = DriverManager.getConnection(jdbcURL, user, password);
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT name FROM IDENTITY");
if(rs.next())
{
name = rs.getString("name");
}
}
catch(java.sql.SQLException e)
{
System.out.println("The exception is " + e.toString());
}
Toast.makeText(getApplicationContext(), name, 1).show();
return name;
}
I'll appreciate any help. Thank you.
Add following permission to your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"></uses-permission>